深入理解linux内核-第2版-英文


I l@ve RuBoard • Table of Contents • Index • Reviews • Reader Reviews • Errata Understanding the Linux Kernel, 2nd Edition By Daniel P. Bovet, Marco Cesati Publisher : O'Reilly Pub Date : December 2002 ISBN : 0-596-00213-0 Pages : 784 The new edition of Understanding the Linux Kernel takes you on a guided tour through the most significant data structures, many algorithms, and programming tricks used in the kernel. The book has been updated to cover version 2.4 of the kernel, which is quite different from version 2.2: the virtual memory system is entirely new, support for multiprocessor systems is improved, and whole new classes of hardware devices have been added. You'll learn what conditions bring out Linux's best performance, and how it meets the challenge of providing good system response during process scheduling, file access, and memory management in a wide variety of environments. I l@ve RuBoard I l@ve RuBoard • Table of Contents • Index • Reviews • Reader Reviews • Errata Understanding the Linux Kernel, 2nd Edition By Daniel P. Bovet, Marco Cesati Publisher : O'Reilly Pub Date : December 2002 ISBN : 0-596-00213-0 Pages : 784 Copyright Preface The Audience for This Book Organization of the Material Overview of the Book Background Information Conventions in This Book How to Contact Us Acknowledgments Chapter 1. Introduction Section 1.1. Linux Versus Other Unix-Like Kernels Section 1.2. Hardware Dependency Section 1.3. Linux Versions Section 1.4. Basic Operating System Concepts Section 1.5. An Overview of the Unix Filesystem Section 1.6. An Overview of Unix Kernels Chapter 2. Memory Addressing Section 2.1. Memory Addresses Section 2.2. Segmentation in Hardware Section 2.3. Segmentation in Linux Section 2.4. Paging in Hardware Section 2.5. Paging in Linux Chapter 3. Processes Section 3.1. Processes, Lightweight Processes, and Threads Section 3.2. Process Descriptor Section 3.3. Process Switch Section 3.4. Creating Processes Section 3.5. Destroying Processes Chapter 4. Interrupts and Exceptions Section 4.1. The Role of Interrupt Signals Section 4.2. Interrupts and Exceptions Section 4.3. Nested Execution of Exception and Interrupt Handlers Section 4.4. Initializing the Interrupt Descriptor Table Section 4.5. Exception Handling Section 4.6. Interrupt Handling Section 4.7. Softirqs, Tasklets, and Bottom Halves Section 4.8. Returning from Interrupts and Exceptions Chapter 5. Kernel Synchronization Section 5.1. Kernel Control Paths Section 5.2. When Synchronization Is Not Necessary Section 5.3. Synchronization Primitives Section 5.4. Synchronizing Accesses to Kernel Data Structures Section 5.5. Examples of Race Condition Prevention Chapter 6. Timing Measurements Section 6.1. Hardware Clocks Section 6.2. The Linux Timekeeping Architecture Section 6.3. CPU's Time Sharing Section 6.4. Updating the Time and Date Section 6.5. Updating System Statistics Section 6.6. Software Timers Section 6.7. System Calls Related to Timing Measurements Chapter 7. Memory Management Section 7.1. Page Frame Management Section 7.2. Memory Area Management Section 7.3. Noncontiguous Memory Area Management Chapter 8. Process Address Space Section 8.1. The Process's Address Space Section 8.2. The Memory Descriptor Section 8.3. Memory Regions Section 8.4. Page Fault Exception Handler Section 8.5. Creating and Deleting a Process Address Space Section 8.6. Managing the Heap Chapter 9. System Calls Section 9.1. POSIX APIs and System Calls Section 9.2. System Call Handler and Service Routines Section 9.3. Kernel Wrapper Routines Chapter 10. Signals Section 10.1. The Role of Signals Section 10.2. Generating a Signal Section 10.3. Delivering a Signal Section 10.4. System Calls Related to Signal Handling Chapter 11. Process Scheduling Section 11.1. Scheduling Policy Section 11.2. The Scheduling Algorithm Section 11.3. System Calls Related to Scheduling Chapter 12. The Virtual Filesystem Section 12.1. The Role of the Virtual Filesystem (VFS) Section 12.2. VFS Data Structures Section 12.3. Filesystem Types Section 12.4. Filesystem Mounting Section 12.5. Pathname Lookup Section 12.6. Implementations of VFS System Calls Section 12.7. File Locking Chapter 13. Managing I/O Devices Section 13.1. I/O Architecture Section 13.2. Device Files Section 13.3. Device Drivers Section 13.4. Block Device Drivers Section 13.5. Character Device Drivers Chapter 14. Disk Caches Section 14.1. The Page Cache Section 14.2. The Buffer Cache Chapter 15. Accessing Files Section 15.1. Reading and Writing a File Section 15.2. Memory Mapping Section 15.3. Direct I/O Transfers Chapter 16. Swapping: Methods for Freeing Memory Section 16.1. What Is Swapping? Section 16.2. Swap Area Section 16.3. The Swap Cache Section 16.4. Transferring Swap Pages Section 16.5. Swapping Out Pages Section 16.6. Swapping in Pages Section 16.7. Reclaiming Page Frame Chapter 17. The Ext2 and Ext3 Filesystems Section 17.1. General Characteristics of Ext2 Section 17.2. Ext2 Disk Data Structures Section 17.3. Ext2 Memory Data Structures Section 17.4. Creating the Ext2 Filesystem Section 17.5. Ext2 Methods Section 17.6. Managing Ext2 Disk Space Section 17.7. The Ext3 Filesystem Chapter 18. Networking Section 18.1. Main Networking Data Structures Section 18.2. System Calls Related to Networking Section 18.3. Sending Packets to the Network Card Section 18.4. Receiving Packets from the Network Card Chapter 19. Process Communication Section 19.1. Pipes Section 19.2. FIFOs Section 19.3. System V IPC Chapter 20. Program Execution Section 20.1. Executable Files Section 20.2. Executable Formats Section 20.3. Execution Domains Section 20.4. The exec Functions Appendix A. System Startup Section A.1. Prehistoric Age: The BIOS Section A.2. Ancient Age: The Boot Loader Section A.3. Middle Ages: The setup( ) Function Section A.4. Renaissance: The startup_32( ) Functions Section A.5. Modern Age: The start_kernel( ) Function Appendix B. Modules Section B.1. To Be (a Module) or Not to Be? Section B.2. Module Implementation Section B.3. Linking and Unlinking Modules Section B.4. Linking Modules on Demand Appendix C. Source Code Structure Bibliography Books on Unix Kernels Books on the Linux Kernel Books on PC Architecture and Technical Manuals on Intel Microprocessors Other Online Documentation Sources Colophon Index I l@ve RuBoard I l@ve RuBoard Copyright Copyright © 2003 O'Reilly & Associates, Inc. Printed in the United States of America. Published by O'Reilly & Associates, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O'Reilly & Associates books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://safari.oreilly.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or corporate@oreilly.com. Nutshell Handbook, the Nutshell Handbook logo, and the O'Reilly logo are registered trademarks of O'Reilly & Associates, 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 & Associates, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. The association between the images of the American West and the topic of Linux is a trademark of O'Reilly & Associates, Inc. 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. I l@ve RuBoard I l@ve RuBoard Preface In the spring semester of 1997, we taught a course on operating systems based on Linux 2.0. The idea was to encourage students to read the source code. To achieve this, we assigned term projects consisting of making changes to the kernel and performing tests on the modified version. We also wrote course notes for our students about a few critical features of Linux such as task switching and task scheduling. Out of this work — and with a lot of support from our O'Reilly editor Andy Oram — came the first edition of Understanding the Linux Kernel and the end of 2000, which covered Linux 2.2 with a few anticipations on Linux 2.4. The success encountered by this book encouraged us to continue along this line, and in the fall of 2001 we started planning a second edition covering Linux 2.4. However, Linux 2.4 is quite different from Linux 2.2. Just to mention a few examples, the virtual memory system is entirely new, support for multiprocessor systems is much better, and whole new classes of hardware devices have been added. As a result, we had to rewrite from scratch two-thirds of the book, increasing its size by roughly 25 percent. As in our first experience, we read thousands of lines of code, trying to make sense of them. After all this work, we can say that it was worth the effort. We learned a lot of things you don't find in books, and we hope we have succeeded in conveying some of this information in the following pages. I l@ve RuBoard I l@ve RuBoard The Audience for This Book All people curious about how Linux works and why it is so efficient will find answers here. After reading the book, you will find your way through the many thousands of lines of code, distinguishing between crucial data structures and secondary ones—in short, becoming a true Linux hacker. Our work might be considered a guided tour of the Linux kernel: most of the significant data structures and many algorithms and programming tricks used in the kernel are discussed. In many cases, the relevant fragments of code are discussed line by line. Of course, you should have the Linux source code on hand and should be willing to spend some effort deciphering some of the functions that are not, for sake of brevity, fully described. On another level, the book provides valuable insight to people who want to know more about the critical design issues in a modern operating system. It is not specifically addressed to system administrators or programmers; it is mostly for people who want to understand how things really work inside the machine! As with any good guide, we try to go beyond superficial features. We offer a background, such as the history of major features and the reasons why they were used. I l@ve RuBoard I l@ve RuBoard Organization of the Material When we began to write this book, we were faced with a critical decision: should we refer to a specific hardware platform or skip the hardware-dependent details and concentrate on the pure hardware-independent parts of the kernel? Others books on Linux kernel internals have chosen the latter approach; we decided to adopt the former one for the following reasons: ● Efficient kernels take advantage of most available hardware features, such as addressing techniques, caches, processor exceptions, special instructions, processor control registers, and so on. If we want to convince you that the kernel indeed does quite a good job in performing a specific task, we must first tell what kind of support comes from the hardware. ● Even if a large portion of a Unix kernel source code is processor-independent and coded in C language, a small and critical part is coded in assembly language. A thorough knowledge of the kernel therefore requires the study of a few assembly language fragments that interact with the hardware. When covering hardware features, our strategy is quite simple: just sketch the features that are totally hardware-driven while detailing those that need some software support. In fact, we are interested in kernel design rather than in computer architecture. Our next step in choosing our path consisted of selecting the computer system to describe. Although Linux is now running on several kinds of personal computers and workstations, we decided to concentrate on the very popular and cheap IBM-compatible personal computers—and thus on the 80 x 86 microprocessors and on some support chips included in these personal computers. The term 80 x 86 microprocessor will be used in the forthcoming chapters to denote the Intel 80386, 80486, Pentium, Pentium Pro, Pentium II, Pentium III, and Pentium 4 microprocessors or compatible models. In a few cases, explicit references will be made to specific models. One more choice we had to make was the order to follow in studying Linux components. We tried a bottom-up approach: start with topics that are hardware-dependent and end with those that are totally hardware-independent. In fact, we'll make many references to the 80 x 86 microprocessors in the first part of the book, while the rest of it is relatively hardware- independent. One significant exception is made in Chapter 13. In practice, following a bottom-up approach is not as simple as it looks, since the areas of memory management, process management, and filesystems are intertwined; a few forward references—that is, references to topics yet to be explained—are unavoidable. Each chapter starts with a theoretical overview of the topics covered. The material is then presented according to the bottom-up approach. We start with the data structures needed to support the functionalities described in the chapter. Then we usually move from the lowest level of functions to higher levels, often ending by showing how system calls issued by user applications are supported. Level of Description Linux source code for all supported architectures is contained in more than 8,000 C and assembly language files stored in about 530 subdirectories; it consists of roughly 4 million lines of code, which occupy over 144 megabytes of disk space. Of course, this book can cover only a very small portion of that code. Just to figure out how big the Linux source is, consider that the whole source code of the book you are reading occupies less than 3 megabytes of disk space. Therefore, we would need more than 40 books like this to list all code, without even commenting on it! So we had to make some choices about the parts to describe. This is a rough assessment of our decisions: ● We describe process and memory management fairly thoroughly. ● We cover the Virtual Filesystem and the Ext2 and Ext3 filesystems, although many functions are just mentioned without detailing the code; we do not discuss other filesystems supported by Linux. ● We describe device drivers, which account for a good part of the kernel, as far as the kernel interface is concerned, but do not attempt analysis of each specific driver, including the terminal drivers. ● We cover the inner layers of networking in a rather sketchy way, since this area deserves a whole new book by itself. The book describes the official 2.4.18 version of the Linux kernel, which can be downloaded from the web site, http://www.kernel.org. Be aware that most distributions of GNU/Linux modify the official kernel to implement new features or to improve its efficiency. In a few cases, the source code provided by your favorite distribution might differ significantly from the one described in this book. In many cases, the original code has been rewritten in an easier-to-read but less efficient way. This occurs at time-critical points at which sections of programs are often written in a mixture of hand-optimized C and Assembly code. Once again, our aim is to provide some help in studying the original Linux code. While discussing kernel code, we often end up describing the underpinnings of many familiar features that Unix programmers have heard of and about which they may be curious (shared and mapped memory, signals, pipes, symbolic links, etc.). I l@ve RuBoard I l@ve RuBoard Overview of the Book To make life easier, Chapter 1 presents a general picture of what is inside a Unix kernel and how Linux competes against other well-known Unix systems. The heart of any Unix kernel is memory management. Chapter 2 explains how 80 x 86 processors include special circuits to address data in memory and how Linux exploits them. Processes are a fundamental abstraction offered by Linux and are introduced in Chapter 3. Here we also explain how each process runs either in an unprivileged User Mode or in a privileged Kernel Mode. Transitions between User Mode and Kernel Mode happen only through well-established hardware mechanisms called interrupts and exceptions. These are introduced in Chapter 4. In many occasions, the kernel has to deal with bursts of interrupts coming from different devices. Synchronization mechanisms are needed so that all these requests can be serviced in an interleaved way by the kernel: they are discussed in Chapter 5 for both uniprocessor and multiprocessor systems. One type of interrupt is crucial for allowing Linux to take care of elapsed time; further details can be found in Chapter 6. Next we focus again on memory: Chapter 7 describes the sophisticated techniques required to handle the most precious resource in the system (besides the processors, of course), available memory. This resource must be granted both to the Linux kernel and to the user applications. Chapter 8 shows how the kernel copes with the requests for memory issued by greedy application programs. Chapter 9 explains how a process running in User Mode makes requests to the kernel, while Chapter 10 describes how a process may send synchronization signals to other processes. Chapter 11 explains how Linux executes, in turn, every active process in the system so that all of them can progress toward their completions. Now we are ready to move on to another essential topic, how Linux implements the filesystem. A series of chapters cover this topic. Chapter 12 introduces a general layer that supports many different filesystems. Some Linux files are special because they provide trapdoors to reach hardware devices; Chapter 13 offers insights on these special files and on the corresponding hardware device drivers. Another issue to consider is disk access time; Chapter 14 shows how a clever use of RAM reduces disk accesses, therefore improving system performance significantly. Building on the material covered in these last chapters, we can now explain in Chapter 15 how user applications access normal files. Chapter 16 completes our discussion of Linux memory management and explains the techniques used by Linux to ensure that enough memory is always available. The last chapter dealing with files is Chapter 17 which illustrates the most frequently used Linux filesystem, namely Ext2 and its recent evolution, Ext3. Chapter 18 deals with the lower layers of networking. The last two chapters end our detailed tour of the Linux kernel: Chapter 19 introduces communication mechanisms other than signals available to User Mode processes; Chapter 20 explains how user applications are started. Last, but not least, are the appendixes: Appendix A sketches out how Linux is booted, while Appendix B describes how to dynamically reconfigure the running kernel, adding and removing functionalities as needed. Appendix C is just a list of the directories that contain the Linux source code. I l@ve RuBoard I l@ve RuBoard Background Information No prerequisites are required, except some skill in C programming language and perhaps some knowledge of Assembly language. I l@ve RuBoard I l@ve RuBoard Conventions in This Book The following is a list of typographical conventions used in this book: Constant Width Is used to show the contents of code files or the output from commands, and to indicate source code keywords that appear in code. Italic Is used for file and directory names, program and command names, command-line options, URLs, and for emphasizing new terms. I l@ve RuBoard I l@ve RuBoard How to Contact Us Please address comments and questions concerning this book to the publisher: O'Reilly & Associates, 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, or any additional information. You can access this page at: http://www.oreilly.com/catalog/linuxkernel2/ 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 I l@ve RuBoard I l@ve RuBoard Acknowledgments This book would not have been written without the precious help of the many students of the University of Rome school of engineering "Tor Vergata" who took our course and tried to decipher lecture notes about the Linux kernel. Their strenuous efforts to grasp the meaning of the source code led us to improve our presentation and correct many mistakes. Andy Oram, our wonderful editor at O'Reilly & Associates, deserves a lot of credit. He was the first at O'Reilly to believe in this project, and he spent a lot of time and energy deciphering our preliminary drafts. He also suggested many ways to make the book more readable, and he wrote several excellent introductory paragraphs. Many thanks also to the O'Reilly staff, especially Rob Romano, the technical illustrator, and Lenny Muellner, for tools support. We had some prestigious reviewers who read our text quite carefully. The first edition was checked by (in alphabetical order by first name) Alan Cox, Michael Kerrisk, Paul Kinzelman, Raph Levien, and Rik van Riel. Erez Zadok, Jerry Cooperstein, John Goerzen, Michael Kerrisk, Paul Kinzelman, Rik van Riel, and Walt Smith reviewed this second edition. Their comments, together with those of many readers from all over the world, helped us to remove several errors and inaccuracies and have made this book stronger. —Daniel P. Bovet Marco Cesati September 2002 I l@ve RuBoard I l@ve RuBoard Chapter 1. Introduction Linux is a member of the large family of Unix-like operating systems. A relative newcomer experiencing sudden spectacular popularity starting in the late 1990s, Linux joins such well- known commercial Unix operating systems as System V Release 4 (SVR4), developed by AT&T (now owned by the SCO Group); the 4.4 BSD release from the University of California at Berkeley (4.4BSD); Digital Unix from Digital Equipment Corporation (now Hewlett- Packard); AIX from IBM; HP-UX from Hewlett-Packard; Solaris from Sun Microsystems; and Mac OS X from Apple Computer, Inc. Linux was initially developed by Linus Torvalds in 1991 as an operating system for IBM- compatible personal computers based on the Intel 80386 microprocessor. Linus remains deeply involved with improving Linux, keeping it up to date with various hardware developments and coordinating the activity of hundreds of Linux developers around the world. Over the years, developers have worked to make Linux available on other architectures, including Hewlett-Packard's Alpha, Itanium (the recent Intel's 64-bit processor), MIPS, SPARC, Motorola MC680x0, PowerPC, and IBM's zSeries. One of the more appealing benefits to Linux is that it isn't a commercial operating system: its source code under the GNU Public License[1] is open and available to anyone to study (as we will in this book); if you download the code (the official site is http://www.kernel.org) or check the sources on a Linux CD, you will be able to explore, from top to bottom, one of the most successful, modern operating systems. This book, in fact, assumes you have the source code on hand and can apply what we say to your own explorations. [1] The GNU project is coordinated by the Free Software Foundation, Inc. (http://www.gnu.org); its aim is to implement a whole operating system freely usable by everyone. The availability of a GNU C compiler has been essential for the success of the Linux project. Technically speaking, Linux is a true Unix kernel, although it is not a full Unix operating system because it does not include all the Unix applications, such as filesystem utilities, windowing systems and graphical desktops, system administrator commands, text editors, compilers, and so on. However, since most of these programs are freely available under the GNU General Public License, they can be installed onto one of the filesystems supported by Linux. Since the Linux kernel requires so much additional software to provide a useful environment, many Linux users prefer to rely on commercial distributions, available on CD-ROM, to get the code included in a standard Unix system. Alternatively, the code may be obtained from several different FTP sites. The Linux source code is usually installed in the /usr/src/linux directory. In the rest of this book, all file pathnames will refer implicitly to that directory. I l@ve RuBoard I l@ve RuBoard 1.1 Linux Versus Other Unix-Like Kernels The various Unix-like systems on the market, some of which have a long history and show signs of archaic practices, differ in many important respects. All commercial variants were derived from either SVR4 or 4.4BSD, and all tend to agree on some common standards like IEEE's Portable Operating Systems based on Unix (POSIX) and X/Open's Common Applications Environment (CAE). The current standards specify only an application programming interface (API)—that is, a well-defined environment in which user programs should run. Therefore, the standards do not impose any restriction on internal design choices of a compliant kernel.[2] [2] As a matter of fact, several non-Unix operating systems, such as Windows NT, are POSIX-compliant. To define a common user interface, Unix-like kernels often share fundamental design ideas and features. In this respect, Linux is comparable with the other Unix-like operating systems. Reading this book and studying the Linux kernel, therefore, may help you understand the other Unix variants too. The 2.4 version of the Linux kernel aims to be compliant with the IEEE POSIX standard. This, of course, means that most existing Unix programs can be compiled and executed on a Linux system with very little effort or even without the need for patches to the source code. Moreover, Linux includes all the features of a modern Unix operating system, such as virtual memory, a virtual filesystem, lightweight processes, reliable signals, SVR4 interprocess communications, support for Symmetric Multiprocessor (SMP) systems, and so on. By itself, the Linux kernel is not very innovative. When Linus Torvalds wrote the first kernel, he referred to some classical books on Unix internals, like Maurice Bach's The Design of the Unix Operating System (Prentice Hall, 1986). Actually, Linux still has some bias toward the Unix baseline described in Bach's book (i.e., SVR4). However, Linux doesn't stick to any particular variant. Instead, it tries to adopt the best features and design choices of several different Unix kernels. The following list describes how Linux competes against some well-known commercial Unix kernels: Monolithic kernel It is a large, complex do-it-yourself program, composed of several logically different components. In this, it is quite conventional; most commercial Unix variants are monolithic. (A notable exception is Carnegie-Mellon's Mach 3.0, which follows a microkernel approach.) Compiled and statically linked traditional Unix kernels Most modern kernels can dynamically load and unload some portions of the kernel code (typically, device drivers), which are usually called modules. Linux's support for modules is very good, since it is able to automatically load and unload modules on demand. Among the main commercial Unix variants, only the SVR4.2 and Solaris kernels have a similar feature. Kernel threading Some modern Unix kernels, such as Solaris 2.x and SVR4.2/MP, are organized as a set of kernel threads. A kernel thread is an execution context that can be independently scheduled; it may be associated with a user program, or it may run only some kernel functions. Context switches between kernel threads are usually much less expensive than context switches between ordinary processes, since the former usually operate on a common address space. Linux uses kernel threads in a very limited way to execute a few kernel functions periodically; since Linux kernel threads cannot execute user programs, they do not represent the basic execution context abstraction. (That's the topic of the next item.) Multithreaded application support Most modern operating systems have some kind of support for multithreaded applications — that is, user programs that are well designed in terms of many relatively independent execution flows that share a large portion of the application data structures. A multithreaded user application could be composed of many lightweight processes (LWP), which are processes that can operate on a common address space, common physical memory pages, common opened files, and so on. Linux defines its own version of lightweight processes, which is different from the types used on other systems such as SVR4 and Solaris. While all the commercial Unix variants of LWP are based on kernel threads, Linux regards lightweight processes as the basic execution context and handles them via the nonstandard clone( ) system call. Nonpreemptive kernel Linux 2.4 cannot arbitrarily interleave execution flows while they are in privileged mode.[3] Several sections of kernel code assume they can run and modify data structures without fear of being interrupted and having another thread alter those data structures. Usually, fully preemptive kernels are associated with special real- time operating systems. Currently, among conventional, general-purpose Unix systems, only Solaris 2.x and Mach 3.0 are fully preemptive kernels. SVR4.2/MP introduces some fixed preemption points as a method to get limited preemption capability. [3] This restriction has been removed in the Linux 2.5 development version. Multiprocessor support Several Unix kernel variants take advantage of multiprocessor systems. Linux 2.4 supports symmetric multiprocessing (SMP): the system can use multiple processors and each processor can handle any task — there is no discrimination among them. Although a few parts of the kernel code are still serialized by means of a single "big kernel lock," it is fair to say that Linux 2.4 makes a near optimal use of SMP. Filesystem Linux's standard filesystems come in many flavors, You can use the plain old Ext2 filesystem if you don't have specific needs. You might switch to Ext3 if you want to avoid lengthy filesystem checks after a system crash. If you'll have to deal with many small files, the ReiserFS filesystem is likely to be the best choice. Besides Ext3 and ReiserFS, several other journaling filesystems can be used in Linux, even if they are not included in the vanilla Linux tree; they include IBM AIX's Journaling File System (JFS) and Silicon Graphics Irix's XFS filesystem. Thanks to a powerful object- oriented Virtual File System technology (inspired by Solaris and SVR4), porting a foreign filesystem to Linux is a relatively easy task. STREAMS Linux has no analog to the STREAMS I/O subsystem introduced in SVR4, although it is included now in most Unix kernels and has become the preferred interface for writing device drivers, terminal drivers, and network protocols. This somewhat modest assessment does not depict, however, the whole truth. Several features make Linux a wonderfully unique operating system. Commercial Unix kernels often introduce new features to gain a larger slice of the market, but these features are not necessarily useful, stable, or productive. As a matter of fact, modern Unix kernels tend to be quite bloated. By contrast, Linux doesn't suffer from the restrictions and the conditioning imposed by the market, hence it can freely evolve according to the ideas of its designers (mainly Linus Torvalds). Specifically, Linux offers the following advantages over its commercial competitors: ● Linux is free. You can install a complete Unix system at no expense other than the hardware (of course). ● Linux is fully customizable in all its components. Thanks to the General Public License (GPL), you are allowed to freely read and modify the source code of the kernel and of all system programs.[4] [4] Several commercial companies have started to support their products under Linux. However, most of them aren't distributed under an open source license, so you might not be allowed to read or modify their source code. ● Linux runs on low-end, cheap hardware platforms. You can even build a network server using an old Intel 80386 system with 4 MB of RAM. ● Linux is powerful. Linux systems are very fast, since they fully exploit the features of the hardware components. The main Linux goal is efficiency, and indeed many design choices of commercial variants, like the STREAMS I/O subsystem, have been rejected by Linus because of their implied performance penalty. ● Linux has a high standard for source code quality. Linux systems are usually very stable; they have a very low failure rate and system maintenance time. ● The Linux kernel can be very small and compact. It is possible to fit both a kernel image and full root filesystem, including all fundamental system programs, on just one 1.4 MB floppy disk. As far as we know, none of the commercial Unix variants is able to boot from a single floppy disk. ● Linux is highly compatible with many common operating systems. It lets you directly mount filesystems for all versions of MS-DOS and MS Windows, SVR4, OS/2, Mac OS, Solaris, SunOS, NeXTSTEP, many BSD variants, and so on. Linux is also able to operate with many network layers, such as Ethernet (as well as Fast Ethernet and Gigabit Ethernet), Fiber Distributed Data Interface (FDDI), High Performance Parallel Interface (HIPPI), IBM's Token Ring, AT&T WaveLAN, and DEC RoamAbout DS. By using suitable libraries, Linux systems are even able to directly run programs written for other operating systems. For example, Linux is able to execute applications written for MS-DOS, MS Windows, SVR3 and R4, 4.4BSD, SCO Unix, XENIX, and others on the 80 x 86 platform. ● Linux is well supported. Believe it or not, it may be a lot easier to get patches and updates for Linux than for any other proprietary operating system. The answer to a problem often comes back within a few hours after sending a message to some newsgroup or mailing list. Moreover, drivers for Linux are usually available a few weeks after new hardware products have been introduced on the market. By contrast, hardware manufacturers release device drivers for only a few commercial operating systems — usually Microsoft's. Therefore, all commercial Unix variants run on a restricted subset of hardware components. With an estimated installed base of several tens of millions, people who are used to certain features that are standard under other operating systems are starting to expect the same from Linux. In that regard, the demand on Linux developers is also increasing. Luckily, though, Linux has evolved under the close direction of Linus to accommodate the needs of the masses. I l@ve RuBoard I l@ve RuBoard 1.2 Hardware Dependency Linux tries to maintain a neat distinction between hardware-dependent and hardware- independent source code. To that end, both the arch and the include directories include nine subdirectories that correspond to the nine hardware platforms supported. The standard names of the platforms are: alpha Hewlett-Packard's Alpha workstations arm ARM processor-based computers and embedded devices cris "Code Reduced Instruction Set" CPUs used by Axis in its thin-servers, such as web cameras or development boards i386 IBM-compatible personal computers based on 80 x 86 microprocessors ia64 Workstations based on Intel 64-bit Itanium microprocessor m68k Personal computers based on Motorola MC680 x 0 microprocessors mips Workstations based on MIPS microprocessors mips64 Workstations based on 64-bit MIPS microprocessors parisc Workstations based on Hewlett Packard HP 9000 PA-RISC microprocessors ppc Workstations based on Motorola-IBM PowerPC microprocessors s390 32-bit IBM ESA/390 and zSeries mainframes s390 x IBM 64-bit zSeries servers sh SuperH embedded computers developed jointly by Hitachi and STMicroelectronics sparc Workstations based on Sun Microsystems SPARC microprocessors sparc64 Workstations based on Sun Microsystems 64-bit Ultra SPARC microprocessors I l@ve RuBoard I l@ve RuBoard 1.3 Linux Versions Linux distinguishes stable kernels from development kernels through a simple numbering scheme. Each version is characterized by three numbers, separated by periods. The first two numbers are used to identify the version; the third number identifies the release. As shown in Figure 1-1, if the second number is even, it denotes a stable kernel; otherwise, it denotes a development kernel. At the time of this writing, the current stable version of the Linux kernel is 2.4.18, and the current development version is 2.5.22. The 2.4 kernel — which is the basis for this book — was first released in January 2001 and differs considerably from the 2.2 kernel, particularly with respect to memory management. Work on the 2.5 development version started in November 2001. Figure 1-1. Numbering Linux versions New releases of a stable version come out mostly to fix bugs reported by users. The main algorithms and data structures used to implement the kernel are left unchanged.[5] [5] The practice does not always follow the theory. For instance, the virtual memory system has been significantly changed, starting with the 2.4.10 release. Development versions, on the other hand, may differ quite significantly from one another; kernel developers are free to experiment with different solutions that occasionally lead to drastic kernel changes. Users who rely on development versions for running applications may experience unpleasant surprises when upgrading their kernel to a newer release. This book concentrates on the most recent stable kernel that we had available because, among all the new features being tried in experimental kernels, there's no way of telling which will ultimately be accepted and what they'll look like in their final form. I l@ve RuBoard I l@ve RuBoard 1.4 Basic Operating System Concepts Each computer system includes a basic set of programs called the operating system. The most important program in the set is called the kernel. It is loaded into RAM when the system boots and contains many critical procedures that are needed for the system to operate. The other programs are less crucial utilities; they can provide a wide variety of interactive experiences for the user—as well as doing all the jobs the user bought the computer for—but the essential shape and capabilities of the system are determined by the kernel. The kernel provides key facilities to everything else on the system and determines many of the characteristics of higher software. Hence, we often use the term "operating system" as a synonym for "kernel." The operating system must fulfill two main objectives: ● Interact with the hardware components, servicing all low-level programmable elements included in the hardware platform. ● Provide an execution environment to the applications that run on the computer system (the so-called user programs). Some operating systems allow all user programs to directly play with the hardware components (a typical example is MS-DOS). In contrast, a Unix-like operating system hides all low-level details concerning the physical organization of the computer from applications run by the user. When a program wants to use a hardware resource, it must issue a request to the operating system. The kernel evaluates the request and, if it chooses to grant the resource, interacts with the relative hardware components on behalf of the user program. To enforce this mechanism, modern operating systems rely on the availability of specific hardware features that forbid user programs to directly interact with low-level hardware components or to access arbitrary memory locations. In particular, the hardware introduces at least two different execution modes for the CPU: a nonprivileged mode for user programs and a privileged mode for the kernel. Unix calls these User Mode and Kernel Mode, respectively. In the rest of this chapter, we introduce the basic concepts that have motivated the design of Unix over the past two decades, as well as Linux and other operating systems. While the concepts are probably familiar to you as a Linux user, these sections try to delve into them a bit more deeply than usual to explain the requirements they place on an operating system kernel. These broad considerations refer to virtually all Unix-like systems. The other chapters of this book will hopefully help you understand the Linux kernel internals. 1.4.1 Multiuser Systems A multiuser system is a computer that is able to concurrently and independently execute several applications belonging to two or more users. Concurrently means that applications can be active at the same time and contend for the various resources such as CPU, memory, hard disks, and so on. Independently means that each application can perform its task with no concern for what the applications of the other users are doing. Switching from one application to another, of course, slows down each of them and affects the response time seen by the users. Many of the complexities of modern operating system kernels, which we will examine in this book, are present to minimize the delays enforced on each program and to provide the user with responses that are as fast as possible. Multiuser operating systems must include several features: ● An authentication mechanism for verifying the user's identity ● A protection mechanism against buggy user programs that could block other applications running in the system ● A protection mechanism against malicious user programs that could interfere with or spy on the activity of other users ● An accounting mechanism that limits the amount of resource units assigned to each user To ensure safe protection mechanisms, operating systems must use the hardware protection associated with the CPU privileged mode. Otherwise, a user program would be able to directly access the system circuitry and overcome the imposed bounds. Unix is a multiuser system that enforces the hardware protection of system resources. 1.4.2 Users and Groups In a multiuser system, each user has a private space on the machine; typically, he owns some quota of the disk space to store files, receives private mail messages, and so on. The operating system must ensure that the private portion of a user space is visible only to its owner. In particular, it must ensure that no user can exploit a system application for the purpose of violating the private space of another user. All users are identified by a unique number called the User ID, or UID. Usually only a restricted number of persons are allowed to make use of a computer system. When one of these users starts a working session, the operating system asks for a login name and a password. If the user does not input a valid pair, the system denies access. Since the password is assumed to be secret, the user's privacy is ensured. To selectively share material with other users, each user is a member of one or more groups, which are identified by a unique number called a Group ID, or GID. Each file is associated with exactly one group. For example, access can be set so the user owning the file has read and write privileges, the group has read-only privileges, and other users on the system are denied access to the file. Any Unix-like operating system has a special user called root, superuser, or supervisor. The system administrator must log in as root to handle user accounts, perform maintenance tasks such as system backups and program upgrades, and so on. The root user can do almost everything, since the operating system does not apply the usual protection mechanisms to her. In particular, the root user can access every file on the system and can interfere with the activity of every running user program. 1.4.3 Processes All operating systems use one fundamental abstraction: the process. A process can be defined either as "an instance of a program in execution" or as the "execution context" of a running program. In traditional operating systems, a process executes a single sequence of instructions in an address space ; the address space is the set of memory addresses that the process is allowed to reference. Modern operating systems allow processes with multiple execution flows — that is, multiple sequences of instructions executed in the same address space. Multiuser systems must enforce an execution environment in which several processes can be active concurrently and contend for system resources, mainly the CPU. Systems that allow concurrent active processes are said to be multiprogramming or multiprocessing.[6] It is important to distinguish programs from processes; several processes can execute the same program concurrently, while the same process can execute several programs sequentially. [6] Some multiprocessing operating systems are not multiuser; an example is Microsoft's Windows 98. On uniprocessor systems, just one process can hold the CPU, and hence just one execution flow can progress at a time. In general, the number of CPUs is always restricted, and therefore only a few processes can progress at once. An operating system component called the scheduler chooses the process that can progress. Some operating systems allow only nonpreemptive processes, which means that the scheduler is invoked only when a process voluntarily relinquishes the CPU. But processes of a multiuser system must be preemptive ; the operating system tracks how long each process holds the CPU and periodically activates the scheduler. Unix is a multiprocessing operating system with preemptive processes. Even when no user is logged in and no application is running, several system processes monitor the peripheral devices. In particular, several processes listen at the system terminals waiting for user logins. When a user inputs a login name, the listening process runs a program that validates the user password. If the user identity is acknowledged, the process creates another process that runs a shell into which commands are entered. When a graphical display is activated, one process runs the window manager, and each window on the display is usually run by a separate process. When a user creates a graphics shell, one process runs the graphics windows and a second process runs the shell into which the user can enter the commands. For each user command, the shell process creates another process that executes the corresponding program. Unix-like operating systems adopt a process/kernel model. Each process has the illusion that it's the only process on the machine and it has exclusive access to the operating system services. Whenever a process makes a system call (i.e., a request to the kernel), the hardware changes the privilege mode from User Mode to Kernel Mode, and the process starts the execution of a kernel procedure with a strictly limited purpose. In this way, the operating system acts within the execution context of the process in order to satisfy its request. Whenever the request is fully satisfied, the kernel procedure forces the hardware to return to User Mode and the process continues its execution from the instruction following the system call. 1.4.4 Kernel Architecture As stated before, most Unix kernels are monolithic: each kernel layer is integrated into the whole kernel program and runs in Kernel Mode on behalf of the current process. In contrast, microkernel operating systems demand a very small set of functions from the kernel, generally including a few synchronization primitives, a simple scheduler, and an interprocess communication mechanism. Several system processes that run on top of the microkernel implement other operating system-layer functions, like memory allocators, device drivers, and system call handlers. Although academic research on operating systems is oriented toward microkernels, such operating systems are generally slower than monolithic ones, since the explicit message passing between the different layers of the operating system has a cost. However, microkernel operating systems might have some theoretical advantages over monolithic ones. Microkernels force the system programmers to adopt a modularized approach, since each operating system layer is a relatively independent program that must interact with the other layers through well-defined and clean software interfaces. Moreover, an existing microkernel operating system can be easily ported to other architectures fairly easily, since all hardware-dependent components are generally encapsulated in the microkernel code. Finally, microkernel operating systems tend to make better use of random access memory (RAM) than monolithic ones, since system processes that aren't implementing needed functionalities might be swapped out or destroyed. To achieve many of the theoretical advantages of microkernels without introducing performance penalties, the Linux kernel offers modules. A module is an object file whose code can be linked to (and unlinked from) the kernel at runtime. The object code usually consists of a set of functions that implements a filesystem, a device driver, or other features at the kernel's upper layer. The module, unlike the external layers of microkernel operating systems, does not run as a specific process. Instead, it is executed in Kernel Mode on behalf of the current process, like any other statically linked kernel function. The main advantages of using modules include: A modularized approach Since any module can be linked and unlinked at runtime, system programmers must introduce well-defined software interfaces to access the data structures handled by modules. This makes it easy to develop new modules. Platform independence Even if it may rely on some specific hardware features, a module doesn't depend on a fixed hardware platform. For example, a disk driver module that relies on the SCSI standard works as well on an IBM-compatible PC as it does on Hewlett-Packard's Alpha. Frugal main memory usage A module can be linked to the running kernel when its functionality is required and unlinked when it is no longer useful. This mechanism also can be made transparent to the user, since linking and unlinking can be performed automatically by the kernel. No performance penalty Once linked in, the object code of a module is equivalent to the object code of the statically linked kernel. Therefore, no explicit message passing is required when the functions of the module are invoked.[7] [7] A small performance penalty occurs when the module is linked and unlinked. However, this penalty can be compared to the penalty caused by the creation and deletion of system processes in microkernel operating systems. I l@ve RuBoard I l@ve RuBoard 1.5 An Overview of the Unix Filesystem The Unix operating system design is centered on its filesystem, which has several interesting characteristics. We'll review the most significant ones, since they will be mentioned quite often in forthcoming chapters. 1.5.1 Files A Unix file is an information container structured as a sequence of bytes; the kernel does not interpret the contents of a file. Many programming libraries implement higher-level abstractions, such as records structured into fields and record addressing based on keys. However, the programs in these libraries must rely on system calls offered by the kernel. From the user's point of view, files are organized in a tree-structured namespace, as shown in Figure 1-2. Figure 1-2. An example of a directory tree All the nodes of the tree, except the leaves, denote directory names. A directory node contains information about the files and directories just beneath it. A file or directory name consists of a sequence of arbitrary ASCII characters,[8] with the exception of / and of the null character \0. Most filesystems place a limit on the length of a filename, typically no more than 255 characters. The directory corresponding to the root of the tree is called the root directory. By convention, its name is a slash (/). Names must be different within the same directory, but the same name may be used in different directories. [8] Some operating systems allow filenames to be expressed in many different alphabets, based on 16-bit extended coding of graphical characters such as Unicode. Unix associates a current working directory with each process (see Section 1.6.1 later in this chapter); it belongs to the process execution context, and it identifies the directory currently used by the process. To identify a specific file, the process uses a pathname, which consists of slashes alternating with a sequence of directory names that lead to the file. If the first item in the pathname is a slash, the pathname is said to be absolute, since its starting point is the root directory. Otherwise, if the first item is a directory name or filename, the pathname is said to be relative, since its starting point is the process's current directory. While specifying filenames, the notations "." and ".." are also used. They denote the current working directory and its parent directory, respectively. If the current working directory is the root directory, "." and ".." coincide. 1.5.2 Hard and Soft Links A filename included in a directory is called a file hard link, or more simply, a link. The same file may have several links included in the same directory or in different ones, so it may have several filenames. The Unix command: $ ln f1 f2 is used to create a new hard link that has the pathname f2 for a file identified by the pathname f1. Hard links have two limitations: ● Users are not allowed to create hard links for directories. This might transform the directory tree into a graph with cycles, thus making it impossible to locate a file according to its name. ● Links can be created only among files included in the same filesystem. This is a serious limitation, since modern Unix systems may include several filesystems located on different disks and/or partitions, and users may be unaware of the physical divisions between them. To overcome these limitations, soft links (also called symbolic links) have been introduced. Symbolic links are short files that contain an arbitrary pathname of another file. The pathname may refer to any file located in any filesystem; it may even refer to a nonexistent file. The Unix command: $ ln -s f1 f2 creates a new soft link with pathname f2 that refers to pathname f1. When this command is executed, the filesystem extracts the directory part of f2 and creates a new entry in that directory of type symbolic link, with the name indicated by f2. This new file contains the name indicated by pathname f1. This way, each reference to f2 can be translated automatically into a reference to f1. 1.5.3 File Types Unix files may have one of the following types: ● Regular file ● Directory ● Symbolic link ● Block-oriented device file ● Character-oriented device file ● Pipe and named pipe (also called FIFO) ● Socket The first three file types are constituents of any Unix filesystem. Their implementation is described in detail in Chapter 17. Device files are related to I/O devices and device drivers integrated into the kernel. For example, when a program accesses a device file, it acts directly on the I/O device associated with that file (see Chapter 13). Pipes and sockets are special files used for interprocess communication (see Section 1.6.5 later in this chapter; also see Chapter 18 and Chapter 19) 1.5.4 File Descriptor and Inode Unix makes a clear distinction between the contents of a file and the information about a file. With the exception of device and special files, each file consists of a sequence of characters. The file does not include any control information, such as its length or an End-Of- File (EOF) delimiter. All information needed by the filesystem to handle a file is included in a data structure called an inode. Each file has its own inode, which the filesystem uses to identify the file. While filesystems and the kernel functions handling them can vary widely from one Unix system to another, they must always provide at least the following attributes, which are specified in the POSIX standard: ● File type (see the previous section) ● Number of hard links associated with the file ● File length in bytes ● Device ID (i.e., an identifier of the device containing the file) ● Inode number that identifies the file within the filesystem ● User ID of the file owner ● Group ID of the file ● Several timestamps that specify the inode status change time, the last access time, and the last modify time ● Access rights and file mode (see the next section) 1.5.5 Access Rights and File Mode The potential users of a file fall into three classes: ● The user who is the owner of the file ● The users who belong to the same group as the file, not including the owner ● All remaining users (others) There are three types of access rights — Read, Write, and Execute — for each of these three classes. Thus, the set of access rights associated with a file consists of nine different binary flags. Three additional flags, called suid (Set User ID), sgid (Set Group ID), and sticky, define the file mode. These flags have the following meanings when applied to executable files: suid A process executing a file normally keeps the User ID (UID) of the process owner. However, if the executable file has the suid flag set, the process gets the UID of the file owner. sgid A process executing a file keeps the Group ID (GID) of the process group. However, if the executable file has the sgid flag set, the process gets the ID of the file group. sticky An executable file with the sticky flag set corresponds to a request to the kernel to keep the program in memory after its execution terminates.[9] [9] This flag has become obsolete; other approaches based on sharing of code pages are now used (see Chapter 8). When a file is created by a process, its owner ID is the UID of the process. Its owner group ID can be either the GID of the creator process or the GID of the parent directory, depending on the value of the sgid flag of the parent directory. 1.5.6 File-Handling System Calls When a user accesses the contents of either a regular file or a directory, he actually accesses some data stored in a hardware block device. In this sense, a filesystem is a user- level view of the physical organization of a hard disk partition. Since a process in User Mode cannot directly interact with the low-level hardware components, each actual file operation must be performed in Kernel Mode. Therefore, the Unix operating system defines several system calls related to file handling. All Unix kernels devote great attention to the efficient handling of hardware block devices to achieve good overall system performance. In the chapters that follow, we will describe topics related to file handling in Linux and specifically how the kernel reacts to file-related system calls. To understand those descriptions, you will need to know how the main file-handling system calls are used; these are described in the next section. 1.5.6.1 Opening a file Processes can access only "opened" files. To open a file, the process invokes the system call: fd = open(path, flag, mode) The three parameters have the following meanings: path Denotes the pathname (relative or absolute) of the file to be opened. flag Specifies how the file must be opened (e.g., read, write, read/write, append). It can also specify whether a nonexisting file should be created. mode Specifies the access rights of a newly created file. This system call creates an "open file" object and returns an identifier called a file descriptor. An open file object contains: ● Some file-handling data structures, such as a pointer to the kernel buffer memory area where file data will be copied, an offset field that denotes the current position in the file from which the next operation will take place (the so-called file pointer), and so on. ● Some pointers to kernel functions that the process can invoke. The set of permitted functions depends on the value of the flag parameter. We discuss open file objects in detail in Chapter 12. Let's limit ourselves here to describing some general properties specified by the POSIX semantics. ● A file descriptor represents an interaction between a process and an opened file, while an open file object contains data related to that interaction. The same open file object may be identified by several file descriptors in the same process. ● Several processes may concurrently open the same file. In this case, the filesystem assigns a separate file descriptor to each file, along with a separate open file object. When this occurs, the Unix filesystem does not provide any kind of synchronization among the I/O operations issued by the processes on the same file. However, several system calls such as flock( ) are available to allow processes to synchronize themselves on the entire file or on portions of it (see Chapter 12). To create a new file, the process may also invoke the creat( ) system call, which is handled by the kernel exactly like open( ). 1.5.6.2 Accessing an opened file Regular Unix files can be addressed either sequentially or randomly, while device files and named pipes are usually accessed sequentially (see Chapter 13). In both kinds of access, the kernel stores the file pointer in the open file object — that is, the current position at which the next read or write operation will take place. Sequential access is implicitly assumed: the read( ) and write( ) system calls always refer to the position of the current file pointer. To modify the value, a program must explicitly invoke the lseek( ) system call. When a file is opened, the kernel sets the file pointer to the position of the first byte in the file (offset 0). The lseek( ) system call requires the following parameters: newoffset = lseek(fd, offset, whence); which have the following meanings: fd Indicates the file descriptor of the opened file offset Specifies a signed integer value that will be used for computing the new position of the file pointer whence Specifies whether the new position should be computed by adding the offset value to the number 0 (offset from the beginning of the file), the current file pointer, or the position of the last byte (offset from the end of the file) The read( ) system call requires the following parameters: nread = read(fd, buf, count); which have the following meaning: fd Indicates the file descriptor of the opened file buf Specifies the address of the buffer in the process's address space to which the data will be transferred count Denotes the number of bytes to read When handling such a system call, the kernel attempts to read count bytes from the file having the file descriptor fd, starting from the current value of the opened file's offset field. In some cases—end-of-file, empty pipe, and so on—the kernel does not succeed in reading all count bytes. The returned nread value specifies the number of bytes effectively read. The file pointer is also updated by adding nread to its previous value. The write( ) parameters are similar. 1.5.6.3 Closing a file When a process does not need to access the contents of a file anymore, it can invoke the system call: res = close(fd); which releases the open file object corresponding to the file descriptor fd. When a process terminates, the kernel closes all its remaining opened files. 1.5.6.4 Renaming and deleting a file To rename or delete a file, a process does not need to open it. Indeed, such operations do not act on the contents of the affected file, but rather on the contents of one or more directories. For example, the system call: res = rename(oldpath, newpath); changes the name of a file link, while the system call: res = unlink(pathname); decrements the file link count and removes the corresponding directory entry. The file is deleted only when the link count assumes the value 0. I l@ve RuBoard I l@ve RuBoard 1.6 An Overview of Unix Kernels Unix kernels provide an execution environment in which applications may run. Therefore, the kernel must implement a set of services and corresponding interfaces. Applications use those interfaces and do not usually interact directly with hardware resources. 1.6.1 The Process/Kernel Model As already mentioned, a CPU can run in either User Mode or Kernel Mode. Actually, some CPUs can have more than two execution states. For instance, the 80 x 86 microprocessors have four different execution states. But all standard Unix kernels use only Kernel Mode and User Mode. When a program is executed in User Mode, it cannot directly access the kernel data structures or the kernel programs. When an application executes in Kernel Mode, however, these restrictions no longer apply. Each CPU model provides special instructions to switch from User Mode to Kernel Mode and vice versa. A program usually executes in User Mode and switches to Kernel Mode only when requesting a service provided by the kernel. When the kernel has satisfied the program's request, it puts the program back in User Mode. Processes are dynamic entities that usually have a limited life span within the system. The task of creating, eliminating, and synchronizing the existing processes is delegated to a group of routines in the kernel. The kernel itself is not a process but a process manager. The process/kernel model assumes that processes that require a kernel service use specific programming constructs called system calls. Each system call sets up the group of parameters that identifies the process request and then executes the hardware-dependent CPU instruction to switch from User Mode to Kernel Mode. Besides user processes, Unix systems include a few privileged processes called kernel threads with the following characteristics: ● They run in Kernel Mode in the kernel address space. ● They do not interact with users, and thus do not require terminal devices. ● They are usually created during system startup and remain alive until the system is shut down. On a uniprocessor system, only one process is running at a time and it may run either in User or in Kernel Mode. If it runs in Kernel Mode, the processor is executing some kernel routine. Figure 1-3 illustrates examples of transitions between User and Kernel Mode. Process 1 in User Mode issues a system call, after which the process switches to Kernel Mode and the system call is serviced. Process 1 then resumes execution in User Mode until a timer interrupt occurs and the scheduler is activated in Kernel Mode. A process switch takes place and Process 2 starts its execution in User Mode until a hardware device raises an interrupt. As a consequence of the interrupt, Process 2 switches to Kernel Mode and services the interrupt. Figure 1-3. Transitions between User and Kernel Mode Unix kernels do much more than handle system calls; in fact, kernel routines can be activated in several ways: ● A process invokes a system call. ● The CPU executing the process signals an exception, which is an unusual condition such as an invalid instruction. The kernel handles the exception on behalf of the process that caused it. ● A peripheral device issues an interrupt signal to the CPU to notify it of an event such as a request for attention, a status change, or the completion of an I/O operation. Each interrupt signal is dealt by a kernel program called an interrupt handler. Since peripheral devices operate asynchronously with respect to the CPU, interrupts occur at unpredictable times. ● A kernel thread is executed. Since it runs in Kernel Mode, the corresponding program must be considered part of the kernel. 1.6.2 Process Implementation To let the kernel manage processes, each process is represented by a process descriptor that includes information about the current state of the process. When the kernel stops the execution of a process, it saves the current contents of several processor registers in the process descriptor. These include: ● The program counter (PC) and stack pointer (SP) registers ● The general purpose registers ● The floating point registers ● The processor control registers (Processor Status Word) containing information about the CPU state ● The memory management registers used to keep track of the RAM accessed by the process When the kernel decides to resume executing a process, it uses the proper process descriptor fields to load the CPU registers. Since the stored value of the program counter points to the instruction following the last instruction executed, the process resumes execution at the point where it was stopped. When a process is not executing on the CPU, it is waiting for some event. Unix kernels distinguish many wait states, which are usually implemented by queues of process descriptors; each (possibly empty) queue corresponds to the set of processes waiting for a specific event. 1.6.3 Reentrant Kernels All Unix kernels are reentrant. This means that several processes may be executing in Kernel Mode at the same time. Of course, on uniprocessor systems, only one process can progress, but many can be blocked in Kernel Mode when waiting for the CPU or the completion of some I/O operation. For instance, after issuing a read to a disk on behalf of some process, the kernel lets the disk controller handle it, and resumes executing other processes. An interrupt notifies the kernel when the device has satisfied the read, so the former process can resume the execution. One way to provide reentrancy is to write functions so that they modify only local variables and do not alter global data structures. Such functions are called reentrant functions. But a reentrant kernel is not limited just to such reentrant functions (although that is how some real- time kernels are implemented). Instead, the kernel can include nonreentrant functions and use locking mechanisms to ensure that only one process can execute a nonreentrant function at a time. Every process in Kernel Mode acts on its own set of memory locations and cannot interfere with the others. If a hardware interrupt occurs, a reentrant kernel is able to suspend the current running process even if that process is in Kernel Mode. This capability is very important, since it improves the throughput of the device controllers that issue interrupts. Once a device has issued an interrupt, it waits until the CPU acknowledges it. If the kernel is able to answer quickly, the device controller will be able to perform other tasks while the CPU handles the interrupt. Now let's look at kernel reentrancy and its impact on the organization of the kernel. A kernel control path denotes the sequence of instructions executed by the kernel to handle a system call, an exception, or an interrupt. In the simplest case, the CPU executes a kernel control path sequentially from the first instruction to the last. When one of the following events occurs, however, the CPU interleaves the kernel control paths: ● A process executing in User Mode invokes a system call, and the corresponding kernel control path verifies that the request cannot be satisfied immediately; it then invokes the scheduler to select a new process to run. As a result, a process switch occurs. The first kernel control path is left unfinished and the CPU resumes the execution of some other kernel control path. In this case, the two control paths are executed on behalf of two different processes. ● The CPU detects an exception—for example, access to a page not present in RAM—while running a kernel control path. The first control path is suspended, and the CPU starts the execution of a suitable procedure. In our example, this type of procedure can allocate a new page for the process and read its contents from disk. When the procedure terminates, the first control path can be resumed. In this case, the two control paths are executed on behalf of the same process. ● A hardware interrupt occurs while the CPU is running a kernel control path with the interrupts enabled. The first kernel control path is left unfinished and the CPU starts processing another kernel control path to handle the interrupt. The first kernel control path resumes when the interrupt handler terminates. In this case, the two kernel control paths run in the execution context of the same process, and the total elapsed system time is accounted to it. However, the interrupt handler doesn't necessarily operate on behalf of the process. Figure 1-4 illustrates a few examples of noninterleaved and interleaved kernel control paths. Three different CPU states are considered: ● Running a process in User Mode (User) ● Running an exception or a system call handler (Excp) ● Running an interrupt handler (Intr) Figure 1-4. Interleaving of kernel control paths 1.6.4 Process Address Space Each process runs in its private address space. A process running in User Mode refers to private stack, data, and code areas. When running in Kernel Mode, the process addresses the kernel data and code area and uses another stack. Since the kernel is reentrant, several kernel control paths—each related to a different process—may be executed in turn. In this case, each kernel control path refers to its own private kernel stack. While it appears to each process that it has access to a private address space, there are times when part of the address space is shared among processes. In some cases, this sharing is explicitly requested by processes; in others, it is done automatically by the kernel to reduce memory usage. If the same program, say an editor, is needed simultaneously by several users, the program is loaded into memory only once, and its instructions can be shared by all of the users who need it. Its data, of course, must not be shared because each user will have separate data. This kind of shared address space is done automatically by the kernel to save memory. Processes can also share parts of their address space as a kind of interprocess communication, using the "shared memory" technique introduced in System V and supported by Linux. Finally, Linux supports the mmap( ) system call, which allows part of a file or the memory residing on a device to be mapped into a part of a process address space. Memory mapping can provide an alternative to normal reads and writes for transferring data. If the same file is shared by several processes, its memory mapping is included in the address space of each of the processes that share it. 1.6.5 Synchronization and Critical Regions Implementing a reentrant kernel requires the use of synchronization. If a kernel control path is suspended while acting on a kernel data structure, no other kernel control path should be allowed to act on the same data structure unless it has been reset to a consistent state. Otherwise, the interaction of the two control paths could corrupt the stored information. For example, suppose a global variable V contains the number of available items of some system resource. The first kernel control path, A, reads the variable and determines that there is just one available item. At this point, another kernel control path, B, is activated and reads the same variable, which still contains the value 1. Thus, B decrements V and starts using the resource item. Then A resumes the execution; because it has already read the value of V, it assumes that it can decrement V and take the resource item, which B already uses. As a final result, V contains -1, and two kernel control paths use the same resource item with potentially disastrous effects. When the outcome of some computation depends on how two or more processes are scheduled, the code is incorrect. We say that there is a race condition. In general, safe access to a global variable is ensured by using atomic operations. In the previous example, data corruption is not possible if the two control paths read and decrement V with a single, noninterruptible operation. However, kernels contain many data structures that cannot be accessed with a single operation. For example, it usually isn't possible to remove an element from a linked list with a single operation because the kernel needs to access at least two pointers at once. Any section of code that should be finished by each process that begins it before another process can enter it is called a critical region.[10] [10] Synchronization problems have been fully described in other works; we refer the interested reader to books on the Unix operating systems (see the bibliography). These problems occur not only among kernel control paths, but also among processes sharing common data. Several synchronization techniques have been adopted. The following section concentrates on how to synchronize kernel control paths. 1.6.5.1 Nonpreemptive kernels In search of a drastically simple solution to synchronization problems, most traditional Unix kernels are nonpreemptive: when a process executes in Kernel Mode, it cannot be arbitrarily suspended and substituted with another process. Therefore, on a uniprocessor system, all kernel data structures that are not updated by interrupts or exception handlers are safe for the kernel to access. Of course, a process in Kernel Mode can voluntarily relinquish the CPU, but in this case, it must ensure that all data structures are left in a consistent state. Moreover, when it resumes its execution, it must recheck the value of any previously accessed data structures that could be changed. Nonpreemptability is ineffective in multiprocessor systems, since two kernel control paths running on different CPUs can concurrently access the same data structure. 1.6.5.2 Interrupt disabling Another synchronization mechanism for uniprocessor systems consists of disabling all hardware interrupts before entering a critical region and reenabling them right after leaving it. This mechanism, while simple, is far from optimal. If the critical region is large, interrupts can remain disabled for a relatively long time, potentially causing all hardware activities to freeze. Moreover, on a multiprocessor system, this mechanism doesn't work at all. There is no way to ensure that no other CPU can access the same data structures that are updated in the protected critical region. 1.6.5.3 Semaphores A widely used mechanism, effective in both uniprocessor and multiprocessor systems, relies on the use of semaphores. A semaphore is simply a counter associated with a data structure; it is checked by all kernel threads before they try to access the data structure. Each semaphore may be viewed as an object composed of: ● An integer variable ● A list of waiting processes ● Two atomic methods: down( ) and up( ) The down( ) method decrements the value of the semaphore. If the new value is less than 0, the method adds the running process to the semaphore list and then blocks (i.e., invokes the scheduler). The up( ) method increments the value of the semaphore and, if its new value is greater than or equal to 0, reactivates one or more processes in the semaphore list. Each data structure to be protected has its own semaphore, which is initialized to 1. When a kernel control path wishes to access the data structure, it executes the down( ) method on the proper semaphore. If the value of the new semaphore isn't negative, access to the data structure is granted. Otherwise, the process that is executing the kernel control path is added to the semaphore list and blocked. When another process executes the up( ) method on that semaphore, one of the processes in the semaphore list is allowed to proceed. 1.6.5.4 Spin locks In multiprocessor systems, semaphores are not always the best solution to the synchronization problems. Some kernel data structures should be protected from being concurrently accessed by kernel control paths that run on different CPUs. In this case, if the time required to update the data structure is short, a semaphore could be very inefficient. To check a semaphore, the kernel must insert a process in the semaphore list and then suspend it. Since both operations are relatively expensive, in the time it takes to complete them, the other kernel control path could have already released the semaphore. In these cases, multiprocessor operating systems use spin locks. A spin lock is very similar to a semaphore, but it has no process list; when a process finds the lock closed by another process, it "spins" around repeatedly, executing a tight instruction loop until the lock becomes open. Of course, spin locks are useless in a uniprocessor environment. When a kernel control path tries to access a locked data structure, it starts an endless loop. Therefore, the kernel control path that is updating the protected data structure would not have a chance to continue the execution and release the spin lock. The final result would be that the system hangs. 1.6.5.5 Avoiding deadlocks Processes or kernel control paths that synchronize with other control paths may easily enter a deadlocked state. The simplest case of deadlock occurs when process p1 gains access to data structure a and process p2 gains access to b, but p1 then waits for b and p2 waits for a. Other more complex cyclic waits among groups of processes may also occur. Of course, a deadlock condition causes a complete freeze of the affected processes or kernel control paths. As far as kernel design is concerned, deadlocks become an issue when the number of kernel semaphores used is high. In this case, it may be quite difficult to ensure that no deadlock state will ever be reached for all possible ways to interleave kernel control paths. Several operating systems, including Linux, avoid this problem by introducing a very limited number of semaphores and requesting semaphores in an ascending order. 1.6.6 Signals and Interprocess Communication Unix signals provide a mechanism for notifying processes of system events. Each event has its own signal number, which is usually referred to by a symbolic constant such as SIGTERM. There are two kinds of system events: Asynchronous notifications For instance, a user can send the interrupt signal SIGINT to a foreground process by pressing the interrupt keycode (usually CTRL-C) at the terminal. Synchronous errors or exceptions For instance, the kernel sends the signal SIGSEGV to a process when it accesses a memory location at an illegal address. The POSIX standard defines about 20 different signals, two of which are user-definable and may be used as a primitive mechanism for communication and synchronization among processes in User Mode. In general, a process may react to a signal delivery in two possible ways: ● Ignore the signal. ● Asynchronously execute a specified procedure (the signal handler). If the process does not specify one of these alternatives, the kernel performs a default action that depends on the signal number. The five possible default actions are: ● Terminate the process. ● Write the execution context and the contents of the address space in a file (core dump) and terminate the process. ● Ignore the signal. ● Suspend the process. ● Resume the process's execution, if it was stopped. Kernel signal handling is rather elaborate since the POSIX semantics allows processes to temporarily block signals. Moreover, the SIGKILL and SIGSTOP signals cannot be directly handled by the process or ignored. AT&T's Unix System V introduced other kinds of interprocess communication among processes in User Mode, which have been adopted by many Unix kernels: semaphores, message queues, and shared memory. They are collectively known as System V IPC. The kernel implements these constructs as IPC resources. A process acquires a resource by invoking a shmget( ), semget( ), or msgget( ) system call. Just like files, IPC resources are persistent: they must be explicitly deallocated by the creator process, by the current owner, or by a superuser process. Semaphores are similar to those described in Section 1.6.5, earlier in this chapter, except that they are reserved for processes in User Mode. Message queues allow processes to exchange messages by using the msgsnd( ) and msgget( ) system calls, which insert a message into a specific message queue and extract a message from it, respectively. Shared memory provides the fastest way for processes to exchange and share data. A process starts by issuing a shmget( ) system call to create a new shared memory having a required size. After obtaining the IPC resource identifier, the process invokes the shmat( ) system call, which returns the starting address of the new region within the process address space. When the process wishes to detach the shared memory from its address space, it invokes the shmdt( ) system call. The implementation of shared memory depends on how the kernel implements process address spaces. 1.6.7 Process Management Unix makes a neat distinction between the process and the program it is executing. To that end, the fork( ) and _exit( ) system calls are used respectively to create a new process and to terminate it, while an exec( )-like system call is invoked to load a new program. After such a system call is executed, the process resumes execution with a brand new address space containing the loaded program. The process that invokes a fork( ) is the parent, while the new process is its child. Parents and children can find one another because the data structure describing each process includes a pointer to its immediate parent and pointers to all its immediate children. A naive implementation of the fork( ) would require both the parent's data and the parent's code to be duplicated and assign the copies to the child. This would be quite time consuming. Current kernels that can rely on hardware paging units follow the Copy-On-Write approach, which defers page duplication until the last moment (i.e., until the parent or the child is required to write into a page). We shall describe how Linux implements this technique in Section 8.4.4. The _exit( ) system call terminates a process. The kernel handles this system call by releasing the resources owned by the process and sending the parent process a SIGCHLD signal, which is ignored by default. 1.6.7.1 Zombie processes How can a parent process inquire about termination of its children? The wait( ) system call allows a process to wait until one of its children terminates; it returns the process ID (PID) of the terminated child. When executing this system call, the kernel checks whether a child has already terminated. A special zombie process state is introduced to represent terminated processes: a process remains in that state until its parent process executes a wait( ) system call on it. The system call handler extracts data about resource usage from the process descriptor fields; the process descriptor may be released once the data is collected. If no child process has already terminated when the wait( ) system call is executed, the kernel usually puts the process in a wait state until a child terminates. Many kernels also implement a waitpid( ) system call, which allows a process to wait for a specific child process. Other variants of wait( ) system calls are also quite common. It's good practice for the kernel to keep around information on a child process until the parent issues its wait( ) call, but suppose the parent process terminates without issuing that call? The information takes up valuable memory slots that could be used to serve living processes. For example, many shells allow the user to start a command in the background and then log out. The process that is running the command shell terminates, but its children continue their execution. The solution lies in a special system process called init, which is created during system initialization. When a process terminates, the kernel changes the appropriate process descriptor pointers of all the existing children of the terminated process to make them become children of init. This process monitors the execution of all its children and routinely issues wait( ) system calls, whose side effect is to get rid of all zombies. 1.6.7.2 Process groups and login sessions Modern Unix operating systems introduce the notion of process groups to represent a "job" abstraction. For example, in order to execute the command line: $ ls | sort | more a shell that supports process groups, such as bash, creates a new group for the three processes corresponding to ls, sort, and more. In this way, the shell acts on the three processes as if they were a single entity (the job, to be precise). Each process descriptor includes a process group ID field. Each group of processes may have a group leader, which is the process whose PID coincides with the process group ID. A newly created process is initially inserted into the process group of its parent. Modern Unix kernels also introduce login sessions. Informally, a login session contains all processes that are descendants of the process that has started a working session on a specific terminal—usually, the first command shell process created for the user. All processes in a process group must be in the same login session. A login session may have several process groups active simultaneously; one of these process groups is always in the foreground, which means that it has access to the terminal. The other active process groups are in the background. When a background process tries to access the terminal, it receives a SIGTTIN or SIGTTOUT signal. In many command shells, the internal commands bg and fg can be used to put a process group in either the background or the foreground. 1.6.8 Memory Management Memory management is by far the most complex activity in a Unix kernel. More than a third of this book is dedicated just to describing how Linux does it. This section illustrates some of the main issues related to memory management. 1.6.8.1 Virtual memory All recent Unix systems provide a useful abstraction called virtual memory. Virtual memory acts as a logical layer between the application memory requests and the hardware Memory Management Unit (MMU). Virtual memory has many purposes and advantages: ● Several processes can be executed concurrently. ● It is possible to run applications whose memory needs are larger than the available physical memory. ● Processes can execute a program whose code is only partially loaded in memory. ● Each process is allowed to access a subset of the available physical memory. ● Processes can share a single memory image of a library or program. ● Programs can be relocatable — that is, they can be placed anywhere in physical memory. ● Programmers can write machine-independent code, since they do not need to be concerned about physical memory organization. The main ingredient of a virtual memory subsystem is the notion of virtual address space. The set of memory references that a process can use is different from physical memory addresses. When a process uses a virtual address,[11] the kernel and the MMU cooperate to locate the actual physical location of the requested memory item. [11] These addresses have different nomenclatures, depending on the computer architecture. As we'll see in Chapter 2, Intel manuals refer to them as "logical addresses." Today's CPUs include hardware circuits that automatically translate the virtual addresses into physical ones. To that end, the available RAM is partitioned into page frames 4 or 8 KB in length, and a set of Page Tables is introduced to specify how virtual addresses correspond to physical addresses. These circuits make memory allocation simpler, since a request for a block of contiguous virtual addresses can be satisfied by allocating a group of page frames having noncontiguous physical addresses. 1.6.8.2 Random access memory usage All Unix operating systems clearly distinguish between two portions of the random access memory (RAM). A few megabytes are dedicated to storing the kernel image (i.e., the kernel code and the kernel static data structures). The remaining portion of RAM is usually handled by the virtual memory system and is used in three possible ways: ● To satisfy kernel requests for buffers, descriptors, and other dynamic kernel data structures ● To satisfy process requests for generic memory areas and for memory mapping of files ● To get better performance from disks and other buffered devices by means of caches Each request type is valuable. On the other hand, since the available RAM is limited, some balancing among request types must be done, particularly when little available memory is left. Moreover, when some critical threshold of available memory is reached and a page-frame- reclaiming algorithm is invoked to free additional memory, which are the page frames most suitable for reclaiming? As we shall see in Chapter 16, there is no simple answer to this question and very little support from theory. The only available solution lies in developing carefully tuned empirical algorithms. One major problem that must be solved by the virtual memory system is memory fragmentation. Ideally, a memory request should fail only when the number of free page frames is too small. However, the kernel is often forced to use physically contiguous memory areas, hence the memory request could fail even if there is enough memory available but it is not available as one contiguous chunk. 1.6.8.3 Kernel Memory Allocator The Kernel Memory Allocator (KMA) is a subsystem that tries to satisfy the requests for memory areas from all parts of the system. Some of these requests come from other kernel subsystems needing memory for kernel use, and some requests come via system calls from user programs to increase their processes' address spaces. A good KMA should have the following features: ● It must be fast. Actually, this is the most crucial attribute, since it is invoked by all kernel subsystems (including the interrupt handlers). ● It should minimize the amount of wasted memory. ● It should try to reduce the memory fragmentation problem. ● It should be able to cooperate with the other memory management subsystems to borrow and release page frames from them. Several proposed KMAs, which are based on a variety of different algorithmic techniques, include: ● Resource map allocator ● Power-of-two free lists ● McKusick-Karels allocator ● Buddy system ● Mach's Zone allocator ● Dynix allocator ● Solaris's Slab allocator As we shall see in Chapter 7, Linux's KMA uses a Slab allocator on top of a buddy system. 1.6.8.4 Process virtual address space handling The address space of a process contains all the virtual memory addresses that the process is allowed to reference. The kernel usually stores a process virtual address space as a list of memory area descriptors. For example, when a process starts the execution of some program via an exec( )-like system call, the kernel assigns to the process a virtual address space that comprises memory areas for: ● The executable code of the program ● The initialized data of the program ● The uninitialized data of the program ● The initial program stack (i.e., the User Mode stack) ● The executable code and data of needed shared libraries ● The heap (the memory dynamically requested by the program) All recent Unix operating systems adopt a memory allocation strategy called demand paging. With demand paging, a process can start program execution with none of its pages in physical memory. As it accesses a nonpresent page, the MMU generates an exception; the exception handler finds the affected memory region, allocates a free page, and initializes it with the appropriate data. In a similar fashion, when the process dynamically requires memory by using malloc( ) or the brk( ) system call (which is invoked internally by malloc( )), the kernel just updates the size of the heap memory region of the process. A page frame is assigned to the process only when it generates an exception by trying to refer its virtual memory addresses. Virtual address spaces also allow other efficient strategies, such as the Copy-On-Write strategy mentioned earlier. For example, when a new process is created, the kernel just assigns the parent's page frames to the child address space, but marks them read-only. An exception is raised as soon the parent or the child tries to modify the contents of a page. The exception handler assigns a new page frame to the affected process and initializes it with the contents of the original page. 1.6.8.5 Swapping and caching To extend the size of the virtual address space usable by the processes, the Unix operating system uses swap areas on disk. The virtual memory system regards the contents of a page frame as the basic unit for swapping. Whenever a process refers to a swapped-out page, the MMU raises an exception. The exception handler then allocates a new page frame and initializes the page frame with its old contents saved on disk. On the other hand, physical memory is also used as cache for hard disks and other block devices. This is because hard drives are very slow: a disk access requires several milliseconds, which is a very long time compared with the RAM access time. Therefore, disks are often the bottleneck in system performance. As a general rule, one of the policies already implemented in the earliest Unix system is to defer writing to disk as long as possible by loading into RAM a set of disk buffers that correspond to blocks read from disk. The sync( ) system call forces disk synchronization by writing all of the "dirty" buffers (i.e., all the buffers whose contents differ from that of the corresponding disk blocks) into disk. To avoid data loss, all operating systems take care to periodically write dirty buffers back to disk. 1.6.9 Device Drivers The kernel interacts with I/O devices by means of device drivers. Device drivers are included in the kernel and consist of data structures and functions that control one or more devices, such as hard disks, keyboards, mouses, monitors, network interfaces, and devices connected to a SCSI bus. Each driver interacts with the remaining part of the kernel (even with other drivers) through a specific interface. This approach has the following advantages: ● Device-specific code can be encapsulated in a specific module. ● Vendors can add new devices without knowing the kernel source code; only the interface specifications must be known. ● The kernel deals with all devices in a uniform way and accesses them through the same interface. ● It is possible to write a device driver as a module that can be dynamically loaded in the kernel without requiring the system to be rebooted. It is also possible to dynamically unload a module that is no longer needed, therefore minimizing the size of the kernel image stored in RAM. Figure 1-5 illustrates how device drivers interface with the rest of the kernel and with the processes. Figure 1-5. Device driver interface Some user programs (P) wish to operate on hardware devices. They make requests to the kernel using the usual file-related system calls and the device files normally found in the /dev directory. Actually, the device files are the user-visible portion of the device driver interface. Each device file refers to a specific device driver, which is invoked by the kernel to perform the requested operation on the hardware component. At the time Unix was introduced, graphical terminals were uncommon and expensive, so only alphanumeric terminals were handled directly by Unix kernels. When graphical terminals became widespread, ad hoc applications such as the X Window System were introduced that ran as standard processes and accessed the I/O ports of the graphics interface and the RAM video area directly. Some recent Unix kernels, such as Linux 2.4, provide an abstraction for the frame buffer of the graphic card and allow application software to access them without needing to know anything about the I/O ports of the graphics interface (see Section 13.3.1.) I l@ve RuBoard I l@ve RuBoard Chapter 2. Memory Addressing This chapter deals with addressing techniques. Luckily, an operating system is not forced to keep track of physical memory all by itself; today's microprocessors include several hardware circuits to make memory management both more efficient and more robust in case of programming errors. As in the rest of this book, we offer details in this chapter on how 80 x 86 microprocessors address memory chips and how Linux uses the available addressing circuits. You will find, we hope, that when you learn the implementation details on Linux's most popular platform you will better understand both the general theory of paging and how to research the implementation on other platforms. This is the first of three chapters related to memory management; Chapter 7 discusses how the kernel allocates main memory to itself, while Chapter 8 considers how linear addresses are assigned to processes. I l@ve RuBoard I l@ve RuBoard 2.1 Memory Addresses Programmers casually refer to a memory address as the way to access the contents of a memory cell. But when dealing with 80 x 86 microprocessors, we have to distinguish three kinds of addresses: Logical address Included in the machine language instructions to specify the address of an operand or of an instruction. This type of address embodies the well-known 80 x x86 segmented architecture that forces MS-DOS and Windows programmers to divide their programs into segments. Each logical address consists of a segment and an offset (or displacement) that denotes the distance from the start of the segment to the actual address. Linear address (also known as virtual address) A single 32-bit unsigned integer that can be used to address up to 4 GB — that is, up to 4,294,967,296 memory cells. Linear addresses are usually represented in hexadecimal notation; their values range from 0x00000000 to 0xffffffff. Physical address Used to address memory cells in memory chips. They correspond to the electrical signals sent along the address pins of the microprocessor to the memory bus. Physical addresses are represented as 32-bit unsigned integers. The CPU control unit transforms a logical address into a linear address by means of a hardware circuit called a segmentation unit; subsequently, a second hardware circuit called a paging unit transforms the linear address into a physical address (see Figure 2-1). Figure 2-1. Logical address translation In multiprocessor systems, all CPUs share the same memory; this means that RAM chips may be accessed concurrently by independent CPUs. Since read or write operations on a RAM chip must be performed serially, a hardware circuit called a memory arbiter is inserted between the bus and every RAM chip. Its role is to grant access to a CPU if the chip is free and to delay it if the chip is busy servicing a request by another processor. Even uniprocessor systems use memory arbiters, since they include a specialized processor called DMA that operates concurrently with the CPU (see Section 13.1.4). In the case of multiprocessor systems, the structure of the arbiter is more complex since it has more input ports. The dual Pentium, for instance, maintains a two-port arbiter at each chip entrance and requires that the two CPUs exchange synchronization messages before attempting to use the common bus. From the programming point of view, the arbiter is hidden since it is managed by hardware circuits. I l@ve RuBoard I l@ve RuBoard 2.2 Segmentation in Hardware Starting with the 80386 model, Intel microprocessors perform address translation in two different ways called real mode and protected mode. These are described in the next sections. Real mode exists mostly to maintain processor compatibility with older models and to allow the operating system to bootstrap (see Appendix A for a short description of real mode). 2.2.1 Segmentation Registers A logical address consists of two parts: a segment identifier and an offset that specifies the relative address within the segment. The segment identifier is a 16-bit field called the Segment Selector, while the offset is a 32-bit field. To make it easy to retrieve segment selectors quickly, the processor provides segmentation registers whose only purpose is to hold Segment Selectors; these registers are called cs, ss, ds, es, fs, and gs. Although there are only six of them, a program can reuse the same segmentation register for different purposes by saving its content in memory and then restoring it later. Three of the six segmentation registers have specific purposes: cs The code segment register, which points to a segment containing program instructions ss The stack segment register, which points to a segment containing the current program stack ds The data segment register, which points to a segment containing static and external data The remaining three segmentation registers are general purpose and may refer to arbitrary data segments. The cs register has another important function: it includes a 2-bit field that specifies the Current Privilege Level (CPL) of the CPU. The value 0 denotes the highest privilege level, while the value 3 denotes the lowest one. Linux uses only levels 0 and 3, which are respectively called Kernel Mode and User Mode. 2.2.2 Segment Descriptors Each segment is represented by an 8-byte Segment Descriptor (see Figure 2-2) that describes the segment characteristics. Segment Descriptors are stored either in the Global Descriptor Table (GDT ) or in the Local Descriptor Table (LDT ). Figure 2-2. Segment Descriptor format Usually only one GDT is defined, while each process is permitted to have its own LDT if it needs to create additional segments besides those stored in the GDT. The address of the GDT in main memory is contained in the gdtr processor register and the address of the currently used LDT is contained in the ldtr processor register. Each Segment Descriptor consists of the following fields: ● A 32-bit Base field that contains the linear address of the first byte of the segment. ● A G granularity flag. If it is cleared (equal to 0), the segment size is expressed in bytes; otherwise, it is expressed in multiples of 4096 bytes. ● A 20-bit Limit field that denotes the segment length in bytes (segments that have a Limit field equal to zero are considered null). When G is set to 0, the size of a non- null segment may vary between 1 byte and 1 MB; otherwise, it may vary between 4 KB and 4 GB. ● An S system flag. If it is cleared, the segment is a system segment that stores kernel data structures; otherwise, it is a normal code or data segment. ● A 4-bit Type field that characterizes the segment type and its access rights. The following list shows Segment Descriptor types that are widely used. Code Segment Descriptor Indicates that the Segment Descriptor refers to a code segment; it may be included either in the GDT or in the LDT. The descriptor has the S flag set. Data Segment Descriptor Indicates that the Segment Descriptor refers to a data segment; it may be included either in the GDT or in the LDT. The descriptor has the S flag set. Stack segments are implemented by means of generic data segments. Task State Segment Descriptor (TSSD) Indicates that the Segment Descriptor refers to a Task State Segment (TSS) — that is, a segment used to save the contents of the processor registers (see Section 3.3.2); it can appear only in the GDT. The corresponding Type field has the value 11 or 9, depending on whether the corresponding process is currently executing on a CPU. The S flag of such descriptors is set to 0. Local Descriptor Table Descriptor (LDTD) Indicates that the Segment Descriptor refers to a segment containing an LDT; it can appear only in the GDT. The corresponding Type field has the value 2. The S flag of such descriptors is set to 0. The next section shows how 80 x 86 processors are able to decide whether a segment descriptor is stored in the GDT or in the LDT of the process. ● A DPL (Descriptor Privilege Level ) 2-bit field used to restrict accesses to the segment. It represents the minimal CPU privilege level requested for accessing the segment. Therefore, a segment with its DPL set to 0 is accessible only when the CPL is 0 — that is, in Kernel Mode — while a segment with its DPL set to 3 is accessible with every CPL value. ● A Segment-Present flag that is equal to 0 if the segment is currently not stored in main memory. Linux always sets this field to 1, since it never swaps out whole segments to disk. ● An additional flag called D or B depending on whether the segment contains code or data. Its meaning is slightly different in the two cases, but it is basically set (equal to 1) if the addresses used as segment offsets are 32 bits long and it is cleared if they are 16 bits long (see the Intel manual for further details). ● A reserved bit (bit 53) always set to 0. ● An AVL flag that may be used by the operating system but is ignored in Linux. 2.2.3 Fast Access to Segment Descriptors We recall that logical addresses consist of a 16-bit Segment Selector and a 32-bit Offset, and that segmentation registers store only the Segment Selector. To speed up the translation of logical addresses into linear addresses, the 80 x 86 processor provides an additional nonprogrammable register—that is, a register that cannot be set by a programmer—for each of the six programmable segmentation registers. Each nonprogrammable register contains the 8-byte Segment Descriptor (described in the previous section) specified by the Segment Selector contained in the corresponding segmentation register. Every time a Segment Selector is loaded in a segmentation register, the corresponding Segment Descriptor is loaded from memory into the matching nonprogrammable CPU register. From then on, translations of logical addresses referring to that segment can be performed without accessing the GDT or LDT stored in main memory; the processor can just refer directly to the CPU register containing the Segment Descriptor. Accesses to the GDT or LDT are necessary only when the contents of the segmentation register change (see Figure 2-3). Each Segment Selector includes the following fields: ● A 13-bit index (described further in the text following this list) that identifies the corresponding Segment Descriptor entry contained in the GDT or in the LDT ● A TI (Table Indicator) flag that specifies whether the Segment Descriptor is included in the GDT (TI = 0) or in the LDT (TI = 1) ● An RPL (Requestor Privilege Level ) 2-bit field, which is precisely the Current Privilege Level of the CPU when the corresponding Segment Selector is loaded into the cs register[1] [1] The RPL field may also be used to selectively weaken the processor privilege level when accessing data segments; see Intel documentation for details. Figure 2-3. Segment Selector and Segment Descriptor Since a Segment Descriptor is 8 bytes long, its relative address inside the GDT or the LDT is obtained by multiplying the 13-bit index field of the Segment Selector by 8. For instance, if the GDT is at 0x00020000 (the value stored in the gdtr register) and the index specified by the Segment Selector is 2, the address of the corresponding Segment Descriptor is 0x00020000 + (2 x 8), or 0x00020010. The first entry of the GDT is always set to 0. This ensures that logical addresses with a null Segment Selector will be considered invalid, thus causing a processor exception. The maximum number of Segment Descriptors that can be stored in the GDT is 8,191 (i.e., , 213- 1). 2.2.4 Segmentation Unit Figure 2-4 shows in detail how a logical address is translated into a corresponding linear address. The segmentation unit performs the following operations: ● Examines the TI field of the Segment Selector to determine which Descriptor Table stores the Segment Descriptor. This field indicates that the Descriptor is either in the GDT (in which case the segmentation unit gets the base linear address of the GDT from the gdtr register) or in the active LDT (in which case the segmentation unit gets the base linear address of that LDT from the ldtr register). ● Computes the address of the Segment Descriptor from the index field of the Segment Selector. The index field is multiplied by 8 (the size of a Segment Descriptor), and the result is added to the content of the gdtr or ldtr register. ● Adds the offset of the logical address to the Base field of the Segment Descriptor, thus obtaining the linear address. Figure 2-4. Translating a logical address Notice that, thanks to the nonprogrammable registers associated with the segmentation registers, the first two operations need to be performed only when a segmentation register has been changed. I l@ve RuBoard I l@ve RuBoard 2.3 Segmentation in Linux Segmentation has been included in 80 x 86 microprocessors to encourage programmers to split their applications into logically related entities, such as subroutines or global and local data areas. However, Linux uses segmentation in a very limited way. In fact, segmentation and paging are somewhat redundant since both can be used to separate the physical address spaces of processes: segmentation can assign a different linear address space to each process, while paging can map the same linear address space into different physical address spaces. Linux prefers paging to segmentation for the following reasons: ● Memory management is simpler when all processes use the same segment register values — that is, when they share the same set of linear addresses. ● One of the design objectives of Linux is portability to a wide range of architectures; RISC architectures in particular have limited support for segmentation. The 2.4 version of Linux uses segmentation only when required by the 80 x 86 architecture. In particular, all processes use the same logical addresses, so the total number of segments to be defined is quite limited, and it is possible to store all Segment Descriptors in the Global Descriptor Table (GDT). This table is implemented by the array gdt_table referred to by the gdt variable. Local Descriptor Tables are not used by the kernel, although a system call called modify_ldt( ) exists that allows processes to create their own LDTs. This turns out to be useful to applications (such as Wine) that execute segment-oriented Microsoft Windows applications. Here are the segments used by Linux: ● A kernel code segment. The fields of the corresponding Segment Descriptor in the GDT have the following values: ❍ Base = 0x00000000 ❍ Limit = 0xfffff ❍ G (granularity flag) = 1, for segment size expressed in pages ❍ S (system flag) = 1, for normal code or data segment ❍ Type = 0xa, for code segment that can be read and executed ❍ DPL (Descriptor Privilege Level) = 0, for Kernel Mode ❍ D/B (32-bit address flag) = 1, for 32-bit offset addresses Thus, the linear addresses associated with that segment start at 0 and reach the addressing limit of 232 -1. The S and Type fields specify that the segment is a code segment that can be read and executed. Its DPL value is 0, so it can be accessed only in Kernel Mode. The corresponding Segment Selector is defined by the _ _KERNEL_CS macro. To address the segment, the kernel just loads the value yielded by the macro into the cs register. ● A kernel data segment. The fields of the corresponding Segment Descriptor in the GDT have the following values: ❍ Base = 0x00000000 ❍ Limit = 0xfffff ❍ G (granularity flag) = 1, for segment size expressed in pages ❍ S (system flag) = 1, for normal code or data segment ❍ Type = 2, for data segment that can be read and written ❍ DPL (Descriptor Privilege Level) = 0, for Kernel Mode ❍ D/B (32-bit address flag) = 1, for 32-bit offset addresses This segment is identical to the previous one (in fact, they overlap in the linear address space), except for the value of the Type field, which specifies that it is a data segment that can be read and written. The corresponding Segment Selector is defined by the _ _KERNEL_DS macro. ● A user code segment shared by all processes in User Mode. The fields of the corresponding Segment Descriptor in the GDT have the following values: ❍ Base = 0x00000000 ❍ Limit = 0xfffff ❍ G (granularity flag) = 1, for segment size expressed in pages ❍ S (system flag) = 1, for normal code or data segment ❍ Type = 0xa, for code segment that can be read and executed ❍ DPL (Descriptor Privilege Level) = 3, for User Mode ❍ D/B (32-bit address flag) = 1, for 32-bit offset addresses The S and DPL fields specify that the segment is not a system segment and its privilege level is equal to 3; it can thus be accessed both in Kernel Mode and in User Mode. The corresponding Segment Selector is defined by the _ _USER_CS macro. ● A user data segment shared by all processes in User Mode. The fields of the corresponding Segment Descriptor in the GDT have the following values: ❍ Base = 0x00000000 ❍ Limit = 0xfffff ❍ G (granularity flag) = 1, for segment size expressed in pages ❍ S (system flag) = 1, for normal code or data segment ❍ Type = 2, for data segment that can be read and written ❍ DPL (Descriptor Privilege Level) = 3, for User Mode ❍ D/B (32-bit address flag) = 1, for 32-bit offset addresses This segment overlaps the previous one: they are identical, except for the value of Type. The corresponding Segment Selector is defined by the _ _USER_DS macro. ● A Task State Segment (TSS) for each processor. The linear address space corresponding to each TSS is a small subset of the linear address space corresponding to the kernel data segment. All the Task State Segments are sequentially stored in the init_tss array; in particular, the Base field of the TSS descriptor for the nth CPU points to the nth component of the init_tss array. The G (granularity) flag is cleared, while the Limit field is set to 0xeb, since the TSS segment is 236 bytes long. The Type field is set to 9 or 11 (available 32-bit TSS), and the DPL is set to 0, since processes in User Mode are not allowed to access TSS segments. You will find details on how Linux uses TSSs in Section 3.3.2. ● A default Local Descriptor Table (LDT) that is usually shared by all processes. This segment is stored in the default_ldt variable. The default LDT includes a single entry consisting of a null Segment Descriptor. Each processor has its own LDT Segment Descriptor, which usually points to the common default LDT segment; its Base field is set to the address of default_ldt and its Limit field is set to 7. When a process requiring a nonempty LDT is running, the LDT descriptor in the GDT corresponding to the executing CPU is replaced by the descriptor associated with the LDT that was built by the process. You will find more details of this mechanism in Chapter 3. ● Four segments related to the Advanced Power Management (APM) support. APM consists of a set of BIOS routines devoted to the management of the power states of the system. If the kernel supports APM, four entries in the GDT store the descriptors of two data segments and two code segments containing APM-related kernel functions. Figure 2-5. The Global Descriptor Table In conclusion, as shown in Figure 2-5, the GDT includes a set of common descriptors plus a pair of segment descriptors for each existing CPU — one for the TSS segment and one for the LDT segment. For efficiency, some entries in the GDT table are left unused, so that segment descriptors usually accessed together are kept in the same 32-byte line of the hardware cache (see Section 2.4.7 later in this chapter). As stated earlier, the Current Privilege Level of the CPU indicates whether the processor is in User or Kernel Mode and is specified by the RPL field of the Segment Selector stored in the cs register. Whenever the CPL is changed, some segmentation registers must be correspondingly updated. For instance, when the CPL is equal to 3 (User Mode), the ds register must contain the Segment Selector of the user data segment, but when the CPL is equal to 0, the ds register must contain the Segment Selector of the kernel data segment. A similar situation occurs for the ss register. It must refer to a User Mode stack inside the user data segment when the CPL is 3, and it must refer to a Kernel Mode stack inside the kernel data segment when the CPL is 0. When switching from User Mode to Kernel Mode, Linux always makes sure that the ss register contains the Segment Selector of the kernel data segment. I l@ve RuBoard I l@ve RuBoard 2.4 Paging in Hardware The paging unit translates linear addresses into physical ones. It checks the requested access type against the access rights of the linear address. If the memory access is not valid, it generates a Page Fault exception (see Chapter 4 and Chapter 7). For the sake of efficiency, linear addresses are grouped in fixed-length intervals called pages; contiguous linear addresses within a page are mapped into contiguous physical addresses. In this way, the kernel can specify the physical address and the access rights of a page instead of those of all the linear addresses included in it. Following the usual convention, we shall use the term "page" to refer both to a set of linear addresses and to the data contained in this group of addresses. The paging unit thinks of all RAM as partitioned into fixed-length page frames (sometimes referred to as physical pages). Each page frame contains a page — that is, the length of a page frame coincides with that of a page. A page frame is a constituent of main memory, and hence it is a storage area. It is important to distinguish a page from a page frame; the former is just a block of data, which may be stored in any page frame or on disk. The data structures that map linear to physical addresses are called Page Tables; they are stored in main memory and must be properly initialized by the kernel before enabling the paging unit. In 80 x 86 processors, paging is enabled by setting the PG flag of a control register named cr0. When PG = 0, linear addresses are interpreted as physical addresses. 2.4.1 Regular Paging Starting with the 80386, the paging unit of Intel processors handles 4 KB pages. The 32 bits of a linear address are divided into three fields: Directory The most significant 10 bits Table The intermediate 10 bits Offset The least significant 12 bits The translation of linear addresses is accomplished in two steps, each based on a type of translation table. The first translation table is called the Page Directory and the second is called the Page Table. The aim of this two-level scheme is to reduce the amount of RAM required for per-process Page Tables. If a simple one-level Page Table was used, then it would require up to 220 entries (i.e., at 4 bytes per entry, 4 MB of RAM) to represent the Page Table for each process (if the process used a full 4 GB linear address space), even though a process does not use all addresses in that range. The two-level scheme reduces the memory by requiring Page Tables only for those virtual memory regions actually used by a process. Each active process must have a Page Directory assigned to it. However, there is no need to allocate RAM for all Page Tables of a process at once; it is more efficient to allocate RAM for a Page Table only when the process effectively needs it. The physical address of the Page Directory in use is stored in a control register named cr3. The Directory field within the linear address determines the entry in the Page Directory that points to the proper Page Table. The address's Table field, in turn, determines the entry in the Page Table that contains the physical address of the page frame containing the page. The Offset field determines the relative position within the page frame (see Figure 2-6). Since it is 12 bits long, each page consists of 4,096 bytes of data. Figure 2-6. Paging by 80x86 processors Both the Directory and the Table fields are 10 bits long, so Page Directories and Page Tables can include up to 1,024 entries. It follows that a Page Directory can address up to 1024 x 1024 x 4096=232 memory cells, as you'd expect in 32-bit addresses. The entries of Page Directories and Page Tables have the same structure. Each entry includes the following fields: Present flag If it is set, the referred-to page (or Page Table) is contained in main memory; if the flag is 0, the page is not contained in main memory and the remaining entry bits may be used by the operating system for its own purposes. If the entry of a Page Table or Page Directory needed to perform an address translation has the Present flag cleared, the paging unit stores the linear address in a control register named cr2 and generates the exception 14: the Page Fault exception. (We shall see in Chapter 16 how Linux uses this field.) Field containing the 20 most significant bits of a page frame physical address Since each page frame has a 4-KB capacity, its physical address must be a multiple of 4,096 so the 12 least significant bits of the physical address are always equal to 0. If the field refers to a Page Directory, the page frame contains a Page Table; if it refers to a Page Table, the page frame contains a page of data. Accessed flag Sets each time the paging unit addresses the corresponding page frame. This flag may be used by the operating system when selecting pages to be swapped out. The paging unit never resets this flag; this must be done by the operating system. Dirty flag Applies only to the Page Table entries. It is set each time a write operation is performed on the page frame. As for the Accessed flag, Dirty may be used by the operating system when selecting pages to be swapped out. The paging unit never resets this flag; this must be done by the operating system. Read/Write flag Contains the access right (Read/Write or Read) of the page or of the Page Table (see Section 2.4.3 later in this chapter). User/Supervisor flag Contains the privilege level required to access the page or Page Table (see the later section Section 2.4.3). PCD and PWT flags Controls the way the page or Page Table is handled by the hardware cache (see Section 2.4.7 later in this chapter). Page Size flag Applies only to Page Directory entries. If it is set, the entry refers to a 2 MB- or 4 MB- long page frame (see the following sections). Global flag Applies only to Page Table entries. This flag was introduced in the Pentium Pro to prevent frequently used pages from being flushed from the TLB cache (see Section 2.4.8 later in this chapter). It works only if the Page Global Enable (PGE) flag of register cr4 is set. 2.4.2 Extended Paging Starting with the Pentium model, 80 x 86 microprocessors introduce extended paging, which allows page frames to be 4 MB instead of 4 KB in size (see Figure 2-7). Figure 2-7. Extended paging As mentioned in the previous section, extended paging is enabled by setting the Page Size flag of a Page Directory entry. In this case, the paging unit divides the 32 bits of a linear address into two fields: Directory The most significant 10 bits Offset The remaining 22 bits Page Directory entries for extended paging are the same as for normal paging, except that: ● The Page Size flag must be set. ● Only the 10 most significant bits of the 20-bit physical address field are significant. This is because each physical address is aligned on a 4-MB boundary, so the 22 least significant bits of the address are 0. Extended paging coexists with regular paging; it is enabled by setting the PSE flag of the cr4 processor register. Extended paging is used to translate large contiguous linear address ranges into corresponding physical ones; in these cases, the kernel can do without intermediate Page Tables and thus save memory and preserve TLB entries (see Section 2.4.8). 2.4.3 Hardware Protection Scheme The paging unit uses a different protection scheme from the segmentation unit. While 80 x 86 processors allow four possible privilege levels to a segment, only two privilege levels are associated with pages and Page Tables, because privileges are controlled by the User/Supervisor flag mentioned in the earlier section Section 2.4.1. When this flag is 0, the page can be addressed only when the CPL is less than 3 (this means, for Linux, when the processor is in Kernel Mode). When the flag is 1, the page can always be addressed. Furthermore, instead of the three types of access rights (Read, Write, and Execute) associated with segments, only two types of access rights (Read and Write) are associated with pages. If the Read/Write flag of a Page Directory or Page Table entry is equal to 0, the corresponding Page Table or page can only be read; otherwise it can be read and written. 2.4.4 An Example of Regular Paging A simple example will help in clarifying how regular paging works. Let's assume that the kernel assigns the linear address space between 0x20000000 and 0x2003ffff to a running process.[2] This space consists of exactly 64 pages. We don't care about the physical addresses of the page frames containing the pages; in fact, some of them might not even be in main memory. We are interested only in the remaining fields of the Page Table entries. [2] As we shall see in the following chapters, the 3 GB linear address space is an upper limit, but a User Mode process is allowed to reference only a subset of it. Let's start with the 10 most significant bits of the linear addresses assigned to the process, which are interpreted as the Directory field by the paging unit. The addresses start with a 2 followed by zeros, so the 10 bits all have the same value, namely 0x080 or 128 decimal. Thus the Directory field in all the addresses refers to the 129th entry of the process Page Directory. The corresponding entry must contain the physical address of the Page Table assigned to the process (see Figure 2-8). If no other linear addresses are assigned to the process, all the remaining 1,023 entries of the Page Directory are filled with zeros. Figure 2-8. An example of paging The values assumed by the intermediate 10 bits, (that is, the values of the Table field) range from 0 to 0x03f, or from to 63 decimal. Thus, only the first 64 entries of the Page Table are significant. The remaining 960 entries are filled with zeros. Suppose that the process needs to read the byte at linear address 0x20021406. This address is handled by the paging unit as follows: 1. The Directory field 0x80 is used to select entry 0x80 of the Page Directory, which points to the Page Table associated with the process's pages. 2. The Table field 0x21 is used to select entry 0x21 of the Page Table, which points to the page frame containing the desired page. 3. Finally, the Offset field 0x406 is used to select the byte at offset 0x406 in the desired page frame. If the Present flag of the 0x21 entry of the Page Table is cleared, the page is not present in main memory; in this case, the paging unit issues a Page Fault exception while translating the linear address. The same exception is issued whenever the process attempts to access linear addresses outside of the interval delimited by 0x20000000 and 0x2003ffff since the Page Table entries not assigned to the process are filled with zeros; in particular, their Present flags are all cleared. 2.4.5 Three-Level Paging Two-level paging is used by 32-bit microprocessors. But in recent years, several microprocessors (such as Hewlett-Packard's Alpha, Intel's Itanium, and Sun's UltraSPARC) have adopted a 64-bit architecture. In this case, two-level paging is no longer suitable and it is necessary to move up to three-level paging. Let's use a thought experiment to explain why. Start by assuming as large a page size as is reasonable (since you have to account for pages being transferred routinely to and from disk). Let's choose 16 KB for the page size. Since 1 KB covers a range of 210 addresses, 16 KB covers 214 addresses, so the Offset field is 14 bits. This leaves 50 bits of the linear address to be distributed between the Table and the Directory fields. If we now decide to reserve 25 bits for each of these two fields, this means that both the Page Directory and the Page Tables of each process includes 225 entries — that is, more than 32 million entries. Even if RAM is getting cheaper and cheaper, we cannot afford to waste so much memory space just for storing the Page Tables. The solution chosen for the Hewlett-Packard's Alpha microprocessor — one of the first 64-bit CPUs that appeared on the market — is the following: ● Page frames are 8 KB long, so the Offset field is 13 bits long. ● Only the least significant 43 bits of an address are used. (The most significant 21 bits are always set to 0.) ● Three levels of Page Tables are introduced so that the remaining 30 bits of the address can be split into three 10-bit fields (see Figure 2-11 later in this chapter). Thus, the Page Tables include 210 = 1024 entries as in the two-level paging schema examined previously. As we shall see in Section 2.5 later in this chapter, Linux's designers decided to implement a paging model inspired by the Alpha architecture. 2.4.6 The Physical Address Extension (PAE) Paging Mechanism The amount of RAM supported by a processor is limited by the number of address pins connected to the address bus. Older Intel processors from the 80386 to the Pentium used 32- bit physical addresses. In theory, up to 4 GB of RAM could be installed on such systems; in practice, due to the linear address space requirements of User Mode processes, the kernel cannot directly address more than 1 GB of RAM, as we shall see in the later section Section 2.5. However, some demanding applications running on large servers require more than 1 GB of RAM, and in recent years this created a pressure on Intel to expand the amount of RAM supported on the 32-bit 80386 architecture. Intel has satisfied these requests by increasing the number of address pins on its processors from 32 to 36. Starting with the Pentium Pro, all Intel processors are now able to address up to 236 = 64 GB of RAM. However, the increased range of physical addresses can be exploited only by introducing a new paging mechanism that translates 32-bit linear addresses into 36- bit physical ones. With the Pentium Pro processor, Intel introduced a mechanism called Physical Address Extension (PAE). Another mechanism, Page Size Extension (PSE-36), was introduced in the Pentium III processor, but Linux does not use it and we won't discuss it further in this book. PAE is activated by setting the Physical Address Extension (PAE) flag in the cr4 control register. The Page Size Extension (PSE) flag in the cr4 control register enables large page sizes (2 MB when PAE is enabled). Intel has changed the paging mechanism in order to support PAE. ● The 64 GB of RAM are split into 224 distinct page frames, and the physical address field of Page Table entries has been expanded from 20 to 24 bits. Since a PAE Page Table entry must include the 12 flag bits (described in the earlier section Section 2.4.1) and the 24 physical address bits, for a grand total of 36, the Page Table entry size has been doubled from 32 bits to 64 bits. As a result, a 4 KB PAE Page Table includes 512 entries instead of 1,024. ● A new level of Page Table called the Page Directory Pointer Table (PDPT) consisting of four 64-bit entries has been introduced. ● The cr3 control register contains a 27-bit Page Directory Pointer Table base address field. Since PDPTs are stored in the first 4 GB of RAM and aligned to a multiple of 32 bytes (25), 27 bits are sufficient to represent the base address of such tables. ● When mapping linear addresses to 4 KB pages (PS flag cleared in Page Directory entry), the 32 bits of a linear address are interpreted in the following way: cr3 Points to a PDPT bits 31-30 Point to one of 4 possible entries in PDPT bits 29-21 Point to one of 512 possible entries in Page Directory bits 20-12 Point to one of 512 possible entries in Page Table bits 11-0 Offset of 4 KB page ● When mapping linear addresses to 2 MB pages (PS flag set in Page Directory entry), the 32 bits of a linear address are interpreted in the following way: cr3 Points to a PDPT bits 31-30 Point to one of 4 possible entries in PDPT bits 29-21 Point to one of 512 possible entries in Page Directory bits 20-0 Offset of 2 MB page To summarize, once cr3 is set, it is possible to address up to 4 GB of RAM. If we want to address more RAM, we'll have to put a new value in cr3 or change the content of the PDPT. However, the main problem with PAE is that linear addresses are still 32-bits long. This forces programmers to reuse the same linear addresses to map different areas of RAM. We'll sketch how Linux initializes Page Tables when PAE is enabled in the later section, Section 2.5.5.4. 2.4.7 Hardware Cache Today's microprocessors have clock rates of several gigahertz, while dynamic RAM (DRAM) chips have access times in the range of hundreds of clock cycles. This means that the CPU may be held back considerably while executing instructions that require fetching operands from RAM and/or storing results into RAM. Hardware cache memories were introduced to reduce the speed mismatch between CPU and RAM. They are based on the well-known locality principle, which holds both for programs and data structures. This states that because of the cyclic structure of programs and the packing of related data into linear arrays, addresses close to the ones most recently used have a high probability of being used in the near future. It therefore makes sense to introduce a smaller and faster memory that contains the most recently used code and data. For this purpose, a new unit called the line was introduced into the 80 x 86 architecture. It consists of a few dozen contiguous bytes that are transferred in burst mode between the slow DRAM and the fast on-chip static RAM (SRAM) used to implement caches. The cache is subdivided into subsets of lines. At one extreme, the cache can be direct mapped, in which case a line in main memory is always stored at the exact same location in the cache. At the other extreme, the cache is fully associative, meaning that any line in memory can be stored at any location in the cache. But most caches are to some degree N- way set associative, where any line of main memory can be stored in any one of N lines of the cache. For instance, a line of memory can be stored in two different lines of a two-way set associative cache. As shown in Figure 2-9, the cache unit is inserted between the paging unit and the main memory. It includes both a hardware cache memory and a cache controller. The cache memory stores the actual lines of memory. The cache controller stores an array of entries, one entry for each line of the cache memory. Each entry includes a tag and a few flags that describe the status of the cache line. The tag consists of some bits that allow the cache controller to recognize the memory location currently mapped by the line. The bits of the memory physical address are usually split into three groups: the most significant ones correspond to the tag, the middle ones to the cache controller subset index, and the least significant ones to the offset within the line. Figure 2-9. Processor hardware cache When accessing a RAM memory cell, the CPU extracts the subset index from the physical address and compares the tags of all lines in the subset with the high-order bits of the physical address. If a line with the same tag as the high-order bits of the address is found, the CPU has a cache hit; otherwise, it has a cache miss. When a cache hit occurs, the cache controller behaves differently, depending on the access type. For a read operation, the controller selects the data from the cache line and transfers it into a CPU register; the RAM is not accessed and the CPU saves time, which is why the cache system was invented. For a write operation, the controller may implement one of two basic strategies called write-through and write-back. In a write-through, the controller always writes into both RAM and the cache line, effectively switching off the cache for write operations. In a write-back, which offers more immediate efficiency, only the cache line is updated and the contents of the RAM are left unchanged. After a write-back, of course, the RAM must eventually be updated. The cache controller writes the cache line back into RAM only when the CPU executes an instruction requiring a flush of cache entries or when a FLUSH hardware signal occurs (usually after a cache miss). When a cache miss occurs, the cache line is written to memory, if necessary, and the correct line is fetched from RAM into the cache entry. Multiprocessor systems have a separate hardware cache for every processor, and therefore need additional hardware circuitry to synchronize the cache contents. As shown in Figure 2- 10, each CPU has its own local hardware cache. But now updating becomes more time consuming: whenever a CPU modifies its hardware cache, it must check whether the same data is contained in the other hardware cache; if so, it must notify the other CPU to update it with the proper value. This activity is often called cache snooping. Luckily, all this is done at the hardware level and is of no concern to the kernel. Figure 2-10. The caches in a dual processor. Cache technology is rapidly evolving. For example, the first Pentium models included a single on-chip cache called the L1-cache. More recent models also include another larger, slower on-chip cache called the L2-cache. The consistency between the two cache levels is implemented at the hardware level. Linux ignores these hardware details and assumes there is a single cache. The CD flag of the cr0 processor register is used to enable or disable the cache circuitry. The NW flag, in the same register, specifies whether the write-through or the write-back strategy is used for the caches. Another interesting feature of the Pentium cache is that it lets an operating system associate a different cache management policy with each page frame. For this purpose, each Page Directory and each Page Table entry includes two flags: PCD (Page Cache Disable), which specifies whether the cache must be enabled or disabled while accessing data included in the page frame; and PWT (Page Write-Through), which specifies whether the write-back or the write-through strategy must be applied while writing data into the page frame. Linux clears the PCD and PWT flags of all Page Directory and Page Table entries; as a result, caching is enabled for all page frames and the write-back strategy is always adopted for writing. 2.4.8 Translation Lookaside Buffers (TLB) Besides general-purpose hardware caches, 80 x 86 processors include other caches called Translation Lookaside Buffers (TLB) to speed up linear address translation. When a linear address is used for the first time, the corresponding physical address is computed through slow accesses to the Page Tables in RAM. The physical address is then stored in a TLB entry so that further references to the same linear address can be quickly translated. In a multiprocessor system, each CPU has its own TLB, called the local TLB of the CPU. Contrary to the L1 cache, the corresponding entries of the TLB need not be synchronized because processes running on the existing CPUs may associate the same linear address with different physical ones. When the cr3 control register of a CPU is modified, the hardware automatically invalidates all entries of the local TLB. I l@ve RuBoard I l@ve RuBoard 2.5 Paging in Linux As we explained earlier in Section 2.4.5, Linux adopted a three-level paging model so paging is feasible on 64-bit architectures. Figure 2-11 shows the model, which defines three types of paging tables. ● Page Global Directory ● Page Middle Directory ● Page Table The Page Global Directory includes the addresses of several Page Middle Directories, which in turn include the addresses of several Page Tables. Each Page Table entry points to a page frame. The linear address is thus split into four parts. Figure 2-11 does not show the bit numbers because the size of each part depends on the computer architecture. Figure 2-11. The Linux paging model Linux's handling of processes relies heavily on paging. In fact, the automatic translation of linear addresses into physical ones makes the following design objectives feasible: ● Assign a different physical address space to each process, ensuring an efficient protection against addressing errors. ● Distinguish pages (groups of data) from page frames (physical addresses in main memory). This allows the same page to be stored in a page frame, then saved to disk and later reloaded in a different page frame. This is the basic ingredient of the virtual memory mechanism (see Chapter 16). As we shall see in Chapter 8, each process has its own Page Global Directory and its own set of Page Tables. When a process switch occurs (see Section 3.3), Linux saves the cr3 control register in the descriptor of the process previously in execution and then loads cr3 with the value stored in the descriptor of the process to be executed next. Thus, when the new process resumes its execution on the CPU, the paging unit refers to the correct set of Page Tables. What happens when this three-level paging model is applied to the Pentium, which uses only two types of Page Tables? Linux essentially eliminates the Page Middle Directory field by saying that it contains zero bits. However, the position of the Page Middle Directory in the sequence of pointers is kept so that the same code can work on 32-bit and 64-bit architectures. The kernel keeps a position for the Page Middle Directory by setting the number of entries in it to 1 and mapping this single entry into the proper entry of the Page Global Directory. However, when Linux uses the Physical Address Extension (PAE) mechanism of the Pentium Pro and later processors, the Linux's Page Global Directory corresponds to the 80 x 86's Page Directory Pointer Table, the Page Middle Directory to the 80 x 86's Page Directory, and the Linux's Page Table to the 80 x 86's Page Table. Mapping logical to linear addresses now becomes a mechanical task, although it is still somewhat complex. The next few sections of this chapter are a rather tedious list of functions and macros that retrieve information the kernel needs to find addresses and manage the tables; most of the functions are one or two lines long. You may want to just skim these sections now, but it is useful to know the role of these functions and macros because you'll see them often in discussions throughout this book. 2.5.1 The Linear Address Fields The following macros simplify Page Table handling: PAGE_SHIFT Specifies the length in bits of the Offset field; when applied to 80 x 86 processors, it yields the value 12. Since all the addresses in a page must fit in the Offset field, the size of a page on 80 x 86 systems is 212 or the familiar 4,096 bytes; the PAGE_SHIFT of 12 can thus be considered the logarithm base 2 of the total page size. This macro is used by PAGE_SIZE to return the size of the page. Finally, the PAGE_MASK macro yields the value 0xfffff000 and is used to mask all the bits of the Offset field. PMD_SHIFT The total length in bits of the Middle Directory and Table fields of a linear address; in other words, the logarithm of the size of the area a Page Middle Directory entry can map. The PMD_SIZE macro computes the size of the area mapped by a single entry of the Page Middle Directory — that is, of a Page Table. The PMD_MASK macro is used to mask all the bits of the Offset and Table fields. When PAE is disabled, PMD_SHIFT yields the value 22 (12 from Offset plus 10 from Table), PMD_SIZE yields 222 or 4 MB, and PMD_MASK yields 0xffc00000. Conversely, when PAE is enabled, PMD_SHIFT yields the value 21 (12 from Offset plus 9 from Table), PMD_SIZE yields 221 or 2 MB, and PMD_MASK yields 0xffe00000. PGDIR_SHIFT Determines the logarithm of the size of the area a Page Global Directory entry can map. The PGDIR_SIZE macro computes the size of the area mapped by a single entry of the Page Global Directory. The PGDIR_MASK macro is used to mask all the bits of the Offset, Table, and Middle Dir fields. When PAE is disabled, PGDIR_SHIFT yields the value 22 (the same value yielded by PMD_SHIFT), PGDIR_SIZE yields 222 or 4 MB, and PGDIR_MASK yields 0xffc00000. Conversely, when PAE is enabled, PGDIR_SHIFT yields the value 30 (12 from Offset plus 9 from Table plus 9 from Middle Dir), PGDIR_SIZE yields 230 or 1 GB, and PGDIR_MASK yields 0xc0000000. PTRS_PER_PTE, PTRS_PER_PMD, and PTRS_PER_PGD Compute the number of entries in the Page Table, Page Middle Directory, and Page Global Directory. They yield the values 1,024, 1, and 1,024, respectively, when PAE is disabled, and the values 4, 512, and 512, respectively, when PAE is enabled 2.5.2 Page Table Handling pte_t, pmd_t, and pgd_t describe the format of, respectively, a Page Table, a Page Middle Directory, and a Page Global Directory entry. They are 32-bit data types, except for pte_t, which is a 64-bit data type when PAE is enabled and a 32-bit data type otherwise. pgprot_t is another 32-bit data type that represents the protection flags associated with a single entry. Four type-conversion macros — _ _ pte( ), _ _ pmd( ), _ _ pgd( ), and _ _ pgprot( ) — cast a unsigned integer into the required type. Four other type-conversion macros — pte_val( ), pmd_val( ), pgd_val( ), and pgprot_val( ) — perform the reverse casting from one of the four previously mentioned specialized types into a unsigned integer. The kernel also provides several macros and functions to read or modify Page Table entries: ● The pte_none( ), pmd_none( ), and pgd_none( ) macros yield the value 1 if the corresponding entry has the value 0; otherwise, they yield the value 0. ● The pte_present( ), pmd_present( ), and pgd_present( ) macros yield the value 1 if the Present flag of the corresponding entry is equal to 1 — that is, if the corresponding page or Page Table is loaded in main memory. ● The pte_clear( ), pmd_clear( ), and pgd_clear( ) macros clear an entry of the corresponding Page Table, thus forbidding a process to use the linear addresses mapped by the Page Table entry. The macros pmd_bad( ) and pgd_bad( ) are used by functions to check Page Global Directory and Page Middle Directory entries passed as input parameters. Each macro yields the value 1 if the entry points to a bad Page Table — that is, if at least one of the following conditions applies: ● The page is not in main memory (Present flag cleared). ● The page allows only Read access (Read/Write flag cleared). ● Either Accessed or Dirty is cleared (Linux always forces these flags to be set for every existing Page Table). No pte_bad( ) macro is defined because it is legal for a Page Table entry to refer to a page that is not present in main memory, not writable, or not accessible at all. Instead, several functions are offered to query the current value of any of the flags included in a Page Table entry: pte_read( ) Returns the value of the User/Supervisor flag (indicating whether the page is accessible in User Mode). pte_write( ) Returns 1 if the Read/Write flag is set (indicating whether the page is writable). pte_exec( ) Returns the value of the User/Supervisor flag (indicating whether the page is accessible in User Mode). Notice that pages on the 80 x 86 processor cannot be protected against code execution. pte_dirty( ) Returns the value of the Dirty flag (indicating whether the page has been modified). pte_young( ) Returns the value of the Accessed flag (indicating whether the page has been accessed). Another group of functions sets the value of the flags in a Page Table entry: pte_wrprotect( ) Clears the Read/Write flag pte_rdprotect and pte_exprotect( ) Clear the User/Supervisor flag pte_mkwrite( ) Sets the Read/Write flag pte_mkread( ) and pte_mkexec( ) Set the User/Supervisor flag pte_mkdirty( ) and pte_mkclean( ) Set the Dirty flag to 1 and to 0, respectively, marking the page as modified or unmodified pte_mkyoung( ) and pte_mkold( ) Set the Accessed flag to 1 and to 0, respectively, marking the page as accessed (young) or nonaccessed (old) pte_modify(p,v) Sets all access rights in a Page Table entry p to a specified value v set_pte, set_pmd, and set_pgd Writes a specified value into a Page Table, Page Middle Directory, and Page Global Directory entry, respectively The ptep_set_wrprotect( ) and ptep_mkdirty( ) functions are similar to pte_wrprotect( ) and pte_mkdirty( ), respectively, except that they act on pointers to a Page Table entry. The ptep_test_and_clear_dirty( ) and ptep_test_and_clear_young( ) functions also act on pointers and are similar to pte_mkclean( ) and pte_mkold( ), respectively, except that they return the old value of the flag. Now come the macros that combine a page address and a group of protection flags into a page entry or perform the reverse operation of extracting the page address from a Page Table entry: mk_ pte Accepts a linear address and a group of access rights as arguments and creates a Page Table entry. mk_ pte_ phys Creates a Page Table entry by combining the physical address and the access rights of the page. pte_ page( ) Returns the address of the descriptor of the page frame referenced by a Page Table entry (see Section 7.1.1). pmd_ page( ) Returns the linear address of a Page Table from its Page Middle Directory entry. pgd_offset(p,a) Receives as parameters a memory descriptor p (see Chapter 8) and a linear address a. The macro yields the address of the entry in a Page Global Directory that corresponds to the address a; the Page Global Directory is found through a pointer within the memory descriptor p. The pgd_offset_k( ) macro is similar, except that it refers to the master kernel Page Tables (see the later section Section 2.5.5). pmd_offset(p,a) Receives as a parameter a Page Global Directory entry p and a linear address a; it yields the address of the entry corresponding to the address a in the Page Middle Directory referenced by p. pte_offset(p,a) Similar to pmd_offset, but p is a Page Middle Directory entry and the macro yields the address of the entry corresponding to a in the Page Table referenced by p. The last group of functions of this long list were introduced to simplify the creation and deletion of Page Table entries. When two-level paging is used (and PAE is disabled), creating or deleting a Page Middle Directory entry is trivial. As we explained earlier in this section, the Page Middle Directory contains a single entry that points to the subordinate Page Table. Thus, the Page Middle Directory entry is the entry within the Page Global Directory too. When dealing with Page Tables, however, creating an entry may be more complex because the Page Table that is supposed to contain it might not exist. In such cases, it is necessary to allocate a new page frame, fill it with zeros, and add the entry. If PAE is enabled, the kernel uses three-level paging. When the kernel creates a new Page Global Directory, it also allocates the four corresponding Page Middle Directories; these are freed only when the parent Page Global Directory is released. As we shall see in Section 7.1, the allocations and deallocations of page frames are expensive operations. Therefore, when the kernel destroys a Page Table, it makes sense to add the corresponding page frame to a suitable memory cache. Linux 2.4.18 already includes some functions and data structures, such as pte_quicklist or pgd_quicklist, to implement such cache; however, the code is not mature and the cache is not used yet. Now comes the last round of functions and macros. As usual, we'll stick to the 80 x 86 architecture. pgd_alloc( m ) Allocates a new Page Global Directory by invoking the get_ pgd_slow( ) function. If PAE is enabled, the latter function also allocates the four children Page Middle Directories. The argument m (the address of a memory descriptor) is ignored on the 80 x 86 architecture. pmd_alloc(m,p,a) Defined so three-level paging systems can allocate a new Page Middle Directory for the linear address a. If PAE is not enabled, the function simply returns the input parameter p — that is, the address of the entry in the Page Global Directory. If PAE is enabled, the function returns the address of the Page Middle Directory that was allocated when the Page Global Directory was created. The argument m is ignored. pte_alloc(m,p,a) Receives as parameters the address of a Page Middle Directory entry p and a linear address a, and returns the address of the Page Table entry corresponding to a. If the Page Middle Directory entry is null, the function must allocate a new Page Table. The page frame is allocated by invoking pte_alloc_one( ). If a new Page Table is allocated, the entry corresponding to a is initialized and the User/Supervisor flag is set. The argument m is ignored. pte_free( ) and pgd_free( ) Release a Page Table. The pmd_free( ) function does nothing, since Page Middle Directories are allocated and deallocated together with their parent Page Global Directory. free_one_pmd( ) Invokes pte_free( ) to release a Page Table and sets the corresponding entry in the Page Middle Directory to NULL. free_one_ pgd( ) Releases all Page Tables of a Page Middle Directory by using free_one_ pmd( ) repeatedly. Then it releases the Page Middle Directory by invoking pmd_free( ). clear_ page_tables( ) Clears the contents of the Page Tables of a process by iteratively invoking free_one_ pgd( ). 2.5.3 Reserved Page Frames The kernel's code and data structures are stored in a group of reserved page frames. A page contained in one of these page frames can never be dynamically assigned or swapped to disk. As a general rule, the Linux kernel is installed in RAM starting from the physical address 0x00100000 — i.e., from the second megabyte. The total number of page frames required depends on how the kernel is configured. A typical configuration yields a kernel that can be loaded in less than 2 MBs of RAM. Why isn't the kernel loaded starting with the first available megabyte of RAM? Well, the PC architecture has several peculiarities that must be taken into account. For example: ● Page frame 0 is used by BIOS to store the system hardware configuration detected during the Power-On Self-Test (POST ); the BIOS of many laptops, moreover, write data on this page frame even after the system is initialized. ● Physical addresses ranging from 0x000a0000 to 0x000fffff are usually reserved to BIOS routines and to map the internal memory of ISA graphics cards. This area is the well-known hole from 640 KB to 1 MB in all IBM-compatible PCs: the physical addresses exist but they are reserved, and the corresponding page frames cannot be used by the operating system. ● Additional page frames within the first megabyte may be reserved by specific computer models. For example, the IBM ThinkPad maps the 0xa0 page frame into the 0x9f one. In the early stage of the boot sequence (see Appendix A), the kernel queries the BIOS and learns the size of the physical memory. In recent computers, the kernel also invokes a BIOS procedure to build a list of physical address ranges and their corresponding memory types. Later, the kernel executes the setup_memory_region( ) function, which fills a table of physical memory regions, shown in Table 2-1. Of course, the kernel builds this table on the basis of the BIOS list, if this is available; otherwise the kernel builds the table following the conservative default setup. All page frames with numbers from 0x9f (LOWMEMSIZE( )) to 0x100 (HIGH_MEMORY) are marked as reserved. Table 2-1. Example of BIOS-provided physical addresses map Start End Type 0x00000000 0x0009ffff Usable 0x000f0000 0x000fffff Reserved 0x00100000 0x07feffff Usable 0x07ff0000 0x07ff2fff ACPI data 0x07ff3000 0x07ffffff ACPI NVS 0xffff0000 0xffffffff Reserved A typical configuration for a computer having 128 MB of RAM is shown in Table 2-1. The physical address range from 0x07ff0000 to 0x07ff2fff stores information about the hardware devices of the system written by the BIOS in the POST phase; during the initialization phase, the kernel copies such information in a suitable kernel data structure, and then considers these page frames usable. Conversely, the physical address range of 0x07ff3000 to 0x07ffffff is mapped on ROM chips of the hardware devices. The physical address range starting from 0xffff0000 is marked as reserved since it is mapped by the hardware to the BIOS's ROM chip (see Appendix A). Notice that the BIOS may not provide information for some physical address ranges (in the table, the range is 0x000a0000 to 0x000effff). To be on the safe side, Linux assumes that such ranges are not usable. To avoid loading the kernel into groups of noncontiguous page frames, Linux prefers to skip the first megabyte of RAM. Clearly, page frames not reserved by the PC architecture will be used by Linux to store dynamically assigned pages. Figure 2-12 shows how the first 2 MB of RAM are filled by Linux. We have assumed that the kernel requires less than one megabyte of RAM (this is a bit optimistic). Figure 2-12. The first 512 page frames (2 MB) in Linux 2.4 The symbol _text, which corresponds to physical address 0x00100000, denotes the address of the first byte of kernel code. The end of the kernel code is similarly identified by the symbol _etext. Kernel data is divided into two groups: initialized and uninitialized. The initialized data starts right after _etext and ends at _edata. The uninitialized data follows and ends up at _end. The symbols appearing in the figure are not defined in Linux source code; they are produced while compiling the kernel.[3] [3] You can find the linear address of these symbols in the file System.map, which is created right after the kernel is compiled. 2.5.4 Process Page Tables The linear address space of a process is divided into two parts: ● Linear addresses from 0x00000000 to 0xbfffffff can be addressed when the process is in either User or Kernel Mode. ● Linear addresses from 0xc0000000 to 0xffffffff can be addressed only when the process is in Kernel Mode. When a process runs in User Mode, it issues linear addresses smaller than 0xc0000000; when it runs in Kernel Mode, it is executing kernel code and the linear addresses issued are greater than or equal to 0xc0000000. In some cases, however, the kernel must access the User Mode linear address space to retrieve or store data. The PAGE_OFFSET macro yields the value 0xc0000000; this is the offset in the linear address space of a process where the kernel lives. In this book, we often refer directly to the number 0xc0000000 instead. The content of the first entries of the Page Global Directory that map linear addresses lower than 0xc0000000 (the first 768 entries with PAE disabled) depends on the specific process. Conversely, the remaining entries should be the same for all processes and equal to the corresponding entries of the kernel master Page Global Directory (see the following section). 2.5.5 Kernel Page Tables The kernel maintains a set of Page Tables for its own use, rooted at a so-called master kernel Page Global Directory. After system initialization, this set of Page Tables are never directly used by any process or kernel thread; rather, the highest entries of the master kernel Page Global Directory are the reference model for the corresponding entries of the Page Global Directories of every regular process in the system. We explain how the kernel ensures that changes to the master kernel Page Global Directory are propagated to the Page Global Directories that are actually used by the processes in the system in Section 8.4.5. We now describe how the kernel initializes its own Page Tables. This is a two-phase activity. In fact, right after the kernel image is loaded into memory, the CPU is still running in real mode; thus, paging is not enabled. In the first phase, the kernel creates a limited 8 MB address space, which is enough for it to install itself in RAM. In the second phase, the kernel takes advantage of all of the existing RAM and sets up the paging tables properly. The next sections examine how this plan is executed. 2.5.5.1 Provisional kernel Page Tables A provisional Page Global Directory is initialized statically during kernel compilation, while the provisional Page Tables are initialized by the startup_32( ) assembly language function defined in arch/i386/kernel/head.S. We won't bother mentioning the Page Middle Directories anymore since they are equated to Page Global Directory entries. PAE support is not enabled at this stage. The Page Global Directory is contained in the swapper_pg_dir variable, while the two Page Tables that span the first 8 MB of RAM are contained in the pg0 and pg1 variables. The objective of this first phase of paging is to allow these 8 MB to be easily addressed both in real mode and protected mode. Therefore, the kernel must create a mapping from both the linear addresses 0x00000000 through 0x007fffff and the linear addresses 0xc0000000 through 0xc07fffff into the physical addresses 0x00000000 through 0x007fffff. In other words, the kernel during its first phase of initialization can address the first 8 MB of RAM by either linear addresses identical to the physical ones or 8 MB worth of linear addresses, starting from 0xc0000000. The kernel creates the desired mapping by filling all the swapper_pg_dir entries with zeroes, except for entries 0, 1, 0 x 300 (decimal 768), and 0 x 301 (decimal 769); the latter two entries span all linear addresses between 0xc0000000 and 0xc07fffff. The 0, 1, 0 x 300, and 0 x 301 entries are initialized as follows: ● The address field of entries 0 and 0 x 300 is set to the physical address of pg0, while the address field of entries 1 and 0 x 301 is set to the physical address of pg1. ● The Present, Read/Write, and User/Supervisor flags are set in all four entries. ● The Accessed, Dirty, PCD, PWD, and Page Size flags are cleared in all four entries. The startup_32( ) assembly language function also enables the paging unit. This is achieved by loading the physical address of swapper_pg_dir into the cr3 control register and by setting the PG flag of the cr0 control register, as shown in the following equivalent code fragment: movl $swapper_pg_dir-0xc0000000,%eax movl %eax,%cr3 /* set the page table pointer.. */ movl %cr0,%eax orl $0x80000000,%eax movl %eax,%cr0 /* ..and set paging (PG) bit */ 2.5.5.2 Final kernel Page Table when RAM size is less than 896 MB The final mapping provided by the kernel Page Tables must transform linear addresses starting from 0xc0000000 into physical addresses starting from 0. The _ pa macro is used to convert a linear address starting from PAGE_OFFSET to the corresponding physical address, while the _va macro does the reverse. The kernel master Page Global Directory is still stored in swapper_pg_dir. It is initialized by the paging_init( ) function, which does the following: 1. Invokes pagetable_init( ) to set up the Page Table entries properly 2. Writes the physical address of swapper_pg_dir in the cr3 control register 3. Invokes flush_tlb_all( ) to invalidate all TLB entries The actions performed by pagetable_init( ) depend on both the amount of RAM present and on the CPU model. Let's start with the simplest case. Our computer has less than 896 MB[4] of RAM, 32-bit physical addresses are sufficient to address all the available RAM, and there is no need to activate the PAE mechanism. (See the earlier section Section 2.4.6.) [4] The highest 128 MB of linear addresses are left available for several kinds of mappings (see sections Section 2.5.6 later in this chapter and Section 7.3). The kernel address space left for mapping the RAM is thus 1 GB - 128 MB = 896 MB. The swapper_pg_dir Page Global Directory is reinitialized by a cycle equivalent to the following: pgd = swapper_pg_dir + 768; address = 0xc0000000; while (address < end) { pe = _PAGE_PRESENT + _PAGE_RW + _PAGE_ACCESSED + _PAGE_DIRTY + _PAGE_PSE + _PAGE_GLOBAL + _ _pa(address); set_pgd(pgd, _ _pgd(pe)); ++pgd; address += 0x400000; } The end variable stores the linear address in the fourth gigabyte corresponding to the end of usable physical memory. We assume that the CPU is a recent 80 x 86 microprocessor supporting 4 MB pages and "global" TLB entries. Notice that the User/Supervisor flags in all Page Global Directory entries referencing linear addresses above 0xc0000000 are cleared, thus denying processes in User Mode access to the kernel address space. The identity mapping of the first 8 MB of physical memory built by the startup_32( ) function is required to complete the initialization phase of the kernel. When this mapping is no longer necessary, the kernel clears the corresponding Page Table entries by invoking the zap_low_mappings( ) function. Actually, this description does not state the whole truth. As we shall see in the later section Section 2.5.6, the kernel also adjusts the entries of Page Tables corresponding to the "fix- mapped linear addresses." 2.5.5.3 Final kernel Page Table when RAM size is between 896 MB and 4096 MB In this case, the RAM cannot be mapped entirely into the kernel linear address space. The best Linux can do during the initialization phase is to map a RAM window having size of 896 MB into the kernel linear address space. If a program needs to address other parts of the existing RAM, some other linear address interval must be mapped to the required RAM. This implies changing the value of some Page Table entries. We'll defer discussing how this kind of dynamic remapping is done in Chapter 7. To initialize the Page Global Directory, the kernel uses the same code as in previous case. 2.5.5.4 Final kernel Page Table when RAM size is more than 4096 MB Let's now consider kernel Page Table initialization for computers with more than 4 GB; more precisely, we deal with cases in which the following happens: ● The CPU model supports Physical Address Extension (PAE). ● The amount of RAM is larger than 4 GB. ● The kernel is compiled with PAE support. Although PAE handles 36-bit physical addresses, linear addresses are still 32-bit addresses. As in the previous case, Linux maps a 896-MB RAM window into the kernel linear address space; the remaining RAM is left unmapped and handled by dynamic remapping, as described in Chapter 7. The main difference with the previous case is that a three-level paging model is used, so the Page Global Directory is initialized as follows: for (i = 0; i < 3; i++) set_pgd(swapper_pg_dir + i, _ _pgd(1 + _ _pa(empty_zero_page))); pgd = swapper_pg_dir + 3; address = 0xc0000000; set_pgd(pgd, _ _pgd(_ _pa(pmd) + 0x1)); while (address < 0xe8000000) { pe = _PAGE_PRESENT + _PAGE_RW + _PAGE_ACCESSED + _PAGE_DIRTY + _PAGE_PSE + _PAGE_GLOBAL + _ _pa(address); set_pmd(pmd, _ _pmd(pe)); pmd++; address += 0x200000; } pgd_base[0] = pgd_base[3]; The kernel initializes the first three entries in the Page Global Directory corresponding to the user linear address space with the address of an empty page (empty_zero_page). The fourth entry is initialized with the address of a Page Middle Directory (pmd). The first 448 entries in the Page Middle Directory (there are 512 entries, but the last 64 are reserved for noncontiguous memory allocation) are filled with the physical address of the first 896 MB of RAM. Notice that all CPU models that support PAE also support large 2 MB pages and global pages. As in the previous case, whenever possible, Linux uses large pages to reduce the number of Page Tables. 2.5.6 Fix-Mapped Linear Addresses We saw that the initial part of the fourth gigabyte of kernel linear addresses maps the physical memory of the system. However, at least 128 MB of linear addresses are always left available because the kernel uses them to implement noncontiguous memory allocation and fix-mapped linear addresses. Noncontiguous memory allocation is just a special way to dynamically allocate and release pages of memory, and is described in Section 7.3. In this section, we focus on fix-mapped linear addresses. Basically, a fix-mapped linear address is a constant linear address like 0xfffffdf0 whose corresponding physical address can be set up in an arbitrary way. Thus, each fix-mapped linear address maps one page frame of the physical memory. Fix-mapped linear addresses are conceptually similar to the linear addresses that map the first 896 MB of RAM. However, a fix-mapped linear address can map any physical address, while the mapping established by the linear addresses in the initial portion of the fourth gigabyte is linear (linear address X maps physical address X-PAGE_OFFSET). With respect to variable pointers, fix-mapped linear addresses are more efficient. In fact, dereferencing a variable pointers requires that one memory access more than dereferencing an immediate constant address. Moreover, checking the value of a variable pointer before dereferencing it is a good programming practice; conversely, the check is never required for a constant linear address. Each fix-mapped linear address is represented by an integer index defined in the enum fixed_addresses data structure: enum fixed_addresses { FIX_APIC_BASE, FIX_IO_APIC_BASE_0, [...] _ _end_of_fixed_addresses }; Fix-mapped linear addresses are placed at the end of the fourth gigabyte of linear addresses. The fix_to_virt( ) function computes the constant linear address starting from the index: inline unsigned long fix_to_virt(const unsigned int idx) { if (idx >= _ _end_of_fixed_addresses) _ _this_fixmap_does_not_exist( ); return (0xffffe000UL - (idx << PAGE_SHIFT)); } Let's assume that some kernel function invokes fix_to_virt(FIX_IOAPIC_BASE_0). Since the function is declared as "inline," the C compiler does not invoke fix_to_virt( ), but just inserts its code in the calling function. Moreover, the check on the index value is never performed at runtime. In fact, FIX_IOAPIC_BASE_0 is a constant, so the compiler can cut away the if statement because its condition is false at compile time. Conversely, if the condition is true or the argument of fix_to_virt( ) is not a constant, the compiler issues an error during the linking phase because the symbol _ _this_fixmap_does_not_exist is not defined elsewhere. Eventually, the compiler computes 0xffffe000-(1<state = TASK_RUNNING; The kernel also uses the set_task_state and set_current_state macros: they set the state of a specified process and of the process currently executed, respectively. Moreover, these macros ensure that the assignment operation is not mixed with other instructions by the compiler or the CPU control unit. Mixing the instruction order may sometimes lead to catastrophic results (see Chapter 5). 3.2.2 Identifying a Process As a general rule, each execution context that can be independently scheduled must have its own process descriptor; therefore, even lightweight processes, which share a large portion of their kernel data structures, have their own task_struct structures. The strict one-to-one correspondence between the process and process descriptor makes the 32-bit process descriptor address[1] a useful means for the kernel to identify processes. These addresses are referred to as process descriptor pointers. Most of the references to processes that the kernel makes are through process descriptor pointers. [1] Technically, these 32 bits are only the offset component of a logical address. However, since Linux uses a single kernel data segment, we can consider the offset to be equivalent to a whole logical address. Furthermore, since the base addresses of the code and data segments are set to 0, we can treat the offset as a linear address. On the other hand, Unix-like operating systems allow users to identify processes by means of a number called the Process ID (or PID), which is stored in the pid field of the process descriptor. PIDs are numbered sequentially: the PID of a newly created process is normally the PID of the previously created process incremented by one. However, for compatibility with traditional Unix systems developed for 16-bit hardware platforms, the maximum PID number allowed on Linux is 32,767. When the kernel creates the 32,768th process in the system, it must start recycling the lower, unused PIDs. Linux associates a different PID with each process or lightweight process in the system. (As we shall see later in this chapter, there is a tiny exception on multiprocessor systems.) This approach allows the maximum flexibility, since every execution context in the system can be uniquely identified. On the other hand, Unix programmers expect threads in the same group to have a common PID. For instance, it should be possible to a send a signal specifying a PID that affects all threads in the group. In fact, the POSIX 1003.1c standard states that all threads of a multithreaded application must have the same PID. To comply with this standard, Linux 2.4 introduces the notion of thread group. A thread group is essentially a collection of lightweight processes that correspond to the threads of a multithreaded application. All descriptors of the lightweight processes in the same thread group are collected in a doubly linked list implemented through the thread_group field of the task_struct structure. The identifier shared by the threads is the PID of the first lightweight process in the group; it is stored in the tgid field of the process descriptors. The getpid( ) system call returns current->tgid instead of current->pid, so all the threads of a multithreaded application share the same identifier. The tgid field has the same value as the pid field, both for normal processes and for lightweight processes not included in a thread group. Therefore, the getpid( ) system call works as usual for them. Later, we'll show you how it is possible to derive a true process descriptor pointer efficiently from its respective PID. Efficiency is important because many system calls such as kill( ) use the PID to denote the affected process. 3.2.2.1 Processor descriptors handling Processes are dynamic entities whose lifetimes range from a few milliseconds to months. Thus, the kernel must be able to handle many processes at the same time, and process descriptors are stored in dynamic memory rather than in the memory area permanently assigned to the kernel. Linux stores two different data structures for each process in a single 8 KB memory area: the process descriptor and the Kernel Mode process stack. In Section 2.3, we learned that a process in Kernel Mode accesses a stack contained in the kernel data segment, which is different from the stack used by the process in User Mode. Since kernel control paths make little use of the stack, only a few thousand bytes of kernel stack are required. Therefore, 8 KB is ample space for the stack and the process descriptor. Figure 3-2 shows how the two data structures are stored in the 2-page (8 KB) memory area. The process descriptor resides at the beginning of the memory area and the stack grows downward from the end. Figure 3-2. Storing the process descriptor and the process kernel stack The esp register is the CPU stack pointer, which is used to address the stack's top location. On Intel systems, the stack starts at the end and grows toward the beginning of the memory area. Right after switching from User Mode to Kernel Mode, the kernel stack of a process is always empty, and therefore the esp register points to the byte immediately following the memory area. The value of the esp is decremented as soon as data is written into the stack. Since the process descriptor is less than 1,000 bytes long, the kernel stack can expand up to 7,200 bytes. The C language allows the process descriptor and the kernel stack of a process to be conveniently represented by means of the following union construct: union task_union { struct task_struct task; unsigned long stack[2048]; }; The process descriptor shown in Figure 3-2 is stored starting at address 0x015fa000, and the stack is stored starting at address 0x015fc000. The value of the esp register points to the current top of the stack at 0x015fa878. The kernel uses the alloc_task_struct and free_task_struct macros to allocate and release the 8 KB memory area storing a process descriptor and a kernel stack. 3.2.2.2 The current macro The close association between the process descriptor and the Kernel Mode stack just described offers a key benefit in terms of efficiency: the kernel can easily obtain the process descriptor pointer of the process currently running on a CPU from the value of the esp register. In fact, since the memory area is 8 KB (213 bytes) long, all the kernel has to do is mask out the 13 least significant bits of esp to obtain the base address of the process descriptor. This is done by the current macro, which produces assembly language instructions like the following: movl $0xffffe000, %ecx andl %esp, %ecx movl %ecx, p After executing these three instructions, p contains the process descriptor pointer of the process running on the CPU that executes the instruction.[2] [2] One drawback to the shared-storage approach is that, for efficiency reasons, the kernel stores the 8-KB memory area in two consecutive page frames with the first page frame aligned to a multiple of 213. This may turn out to be a problem when little dynamic memory is available. The current macro often appears in kernel code as a prefix to fields of the process descriptor. For example, current->pid returns the process ID of the process currently running on the CPU. Another advantage of storing the process descriptor with the stack emerges on multiprocessor systems: the correct current process for each hardware processor can be derived just by checking the stack, as shown previously. Linux 2.0 did not store the kernel stack and the process descriptor together. Instead, it was forced to introduce a global static variable called current to identify the process descriptor of the running process. On multiprocessor systems, it was necessary to define current as an array—one element for each available CPU. 3.2.2.3 The process list To allow an efficient search through processes of a given type (for instance, all processes in a runnable state), the kernel creates several lists of processes. Each list consists of pointers to process descriptors. A list pointer (that is, the field that each process uses to point to the next process) is embedded right in the process descriptor's data structure. When you look at the C-language declaration of the task_struct structure, the descriptors may seem to turn in on themselves in a complicated recursive manner. However, the concept is no more complicated than any list, which is a data structure containing a pointer to the next instance of itself. A circular doubly linked list (see Figure 3-3) links all existing process descriptors; we will call it the process list. The prev_task and next_task fields of each process descriptor are used to implement the list. The head of the list is the init_task descriptor referenced by the first element of the task array; it is the ancestor of all processes, and is called process 0 or swapper (see Section 3.4.2 later in this chapter). The prev_task field of init_task points to the process descriptor inserted last in the list. Figure 3-3. The process list The SET_LINKS and REMOVE_LINKS macros are used to insert and to remove a process descriptor in the process list, respectively. These macros also take care of the parenthood relationship of the process (see Section 3.2.3 later in this chapter). Another useful macro, called for_each_task , scans the whole process list. It is defined as: #define for_each_task(p) \ for (p = &init_task ; (p = p->next_task) != &init_task ; ) The macro is the loop control statement after which the kernel programmer supplies the loop. Notice how the init_task process descriptor just plays the role of list header. The macro starts by moving past init_task to the next task and continues until it reaches init_task again (thanks to the circularity of the list). 3.2.2.4 Doubly linked lists The process list is a special doubly linked list. However, as you may have noticed, the Linux kernel uses hundreds of doubly linked lists that store the various kernel data structures. For each list, a set of primitive operations must be implemented: initializing the list, inserting and deleting an element, scanning the list, and so on. It would be both a waste of programmers' efforts and a waste of memory to replicate the primitive operations for each different list. Therefore, the Linux kernel defines the list_head data structure, whose fields next and prev represent the forward and back pointers of a generic doubly linked list element, respectively. It is important to note, however, that the pointers in a list_head field store the addresses of other list_head fields rather than the addresses of the whole data structures in which the list_head structure is included (see Figure 3-4). Figure 3-4. A doubly linked list built with list_head data structures A new list is created by using the LIST_HEAD(list_name) macro. It declares a new variable named list_name of type list_head, which is the conventional first element of the new list (much as init_task is the conventional first element of the process list). Several functions and macros implement the primitives, including those shown in the following list. list_add(n,p) Inserts an element pointed by n right after the specified element pointed by p (to insert n at the beginning of the list, set p to the address of the conventional first element) list_add_tail(n,h) Inserts an element pointed by n at the end of the list specified by the address h of its conventional first element list_del(p) Deletes an element pointed by p (there is no need to specify the conventional first element of the list) list_empty(p) Checks if the list specified by the address of its conventional first element is empty list_entry(p,t,f) Returns the address of the data structure of type t in which the list_head field that has the name f and the address p is included list_for_each(p,h) Scans the elements of the list specified by the address h of the conventional first element (similar to for_each_task for the process list) 3.2.2.5 The list of TASK_RUNNING processes When looking for a new process to run on the CPU, the kernel has to consider only the runnable processes (that is, the processes in the TASK_RUNNING state). Since it is rather inefficient to scan the whole process list, a doubly linked circular list of TASK_RUNNING processes called runqueue has been introduced. This list is implemented through the run_list field of type list_head in the process descriptor. As in the previous case, the init_task process descriptor plays the role of list header. The nr_running variable stores the total number of runnable processes. The add_to_runqueue( ) function inserts a process descriptor at the beginning of the list, while del_from_runqueue( ) removes a process descriptor from the list. For scheduling purposes, two functions, move_first_runqueue( ) and move_last_runqueue( ), are provided to move a process descriptor to the beginning or the end of the runqueue, respectively. The task_on_runqueue( ) function checks whether a given process is inserted into the runqueue. Finally, the wake_up_process( ) function is used to make a process runnable. It sets the process state to TASK_RUNNING and invokes add_to_runqueue( ) to insert the process in the runqueue list. It also forces the invocation of the scheduler when the process has a dynamic priority larger than that of the current process or, in SMP systems, that of a process currently executing on some other CPU (see Chapter 11). 3.2.2.6 The pidhash table and chained lists In several circumstances, the kernel must be able to derive the process descriptor pointer corresponding to a PID. This occurs, for instance, in servicing the kill( ) system call. When process P1 wishes to send a signal to another process, P2, it invokes the kill( ) system call specifying the PID of P2 as the parameter. The kernel derives the process descriptor pointer from the PID and then extracts the pointer to the data structure that records the pending signals from P2's process descriptor. Scanning the process list sequentially and checking the pid fields of the process descriptors is feasible but rather inefficient. To speed up the search, a pidhash hash table consisting of PIDHASH_SZ elements has been introduced (PIDHASH_SZ is usually set to 1,024). The table entries contain process descriptor pointers. The PID is transformed into a table index using the pid_hashfn macro: #define pid_hashfn(x) ((((x) >> 8) ^ (x)) & (PIDHASH_SZ - 1)) As every basic computer science course explains, a hash function does not always ensure a one-to-one correspondence between PIDs and table indexes. Two different PIDs that hash into the same table index are said to be colliding. Linux uses chaining to handle colliding PIDs; each table entry is a doubly linked list of colliding process descriptors. These lists are implemented by means of the pidhash_next and pidhash_pprev fields in the process descriptor. Figure 3-5 illustrates a pidhash table with two lists. The processes having PIDs 199 and 26,799 hash into the 200th element of the table, while the process having PID 26,800 hashes into the 217th element of the table. Figure 3-5. The pidhash table and chained lists Hashing with chaining is preferable to a linear transformation from PIDs to table indexes because at any given instance, the number of processes in the system is usually far below 32,767 (the maximum allowed PID). It is a waste of storage to define a table consisting of 32,768 entries, if, at any given instance, most such entries are unused. The hash_ pid( ) and unhash_ pid( ) functions are invoked to insert and remove a process in the pidhash table, respectively. The find_task_by_pid( ) function searches the hash table and returns the process descriptor pointer of the process with a given PID (or a null pointer if it does not find the process). 3.2.3 Parenthood Relationships Among Processes Processes created by a program have a parent/child relationship. When a process creates multiple children, these children have sibling relationships. Several fields must be introduced in a process descriptor to represent these relationships. Processes 0 and 1 are created by the kernel; as we shall see later in the chapter, process 1 (init) is the ancestor of all other processes. The descriptor of a process P includes the following fields: p_opptr (original parent) Points to the process descriptor of the process that created P or to the descriptor of process 1 (init) if the parent process no longer exists. Therefore, when a shell user starts a background process and exits the shell, the background process becomes the child of init. p_pptr (parent) Points to the current parent of P (this is the process that must be signaled when the child process terminates); its value usually coincides with that of p_opptr. It may occasionally differ, such as when another process issues a ptrace( ) system call requesting that it be allowed to monitor P (see Section 20.1.5). p_cptr (child) Points to the process descriptor of the youngest child of P — that is, of the process created most recently by it. p_ysptr (younger sibling) Points to the process descriptor of the process that has been created immediately after P by P's current parent. p_osptr (older sibling) Points to the process descriptor of the process that has been created immediately before P by P's current parent. Figure 3-6 illustrates the parent and sibling relationships of a group of processes. Process P0 successively created P1, P2, and P3. Process P3, in turn, created process P4. Starting with p_cptr and using the p_osptr pointers to siblings, P0 is able to retrieve all its children. Figure 3-6. Parenthood relationships among five processes 3.2.4 How Processes Are Organized The runqueue list groups all processes in a TASK_RUNNING state. When it comes to grouping processes in other states, the various states call for different types of treatment, with Linux opting for one of the choices shown in the following list. ● Processes in a TASK_STOPPED or in a TASK_ZOMBIE state are not linked in specific lists. There is no need to group processes in either of these two states, since stopped and zombie processes are accessed only via PID or via linked lists of the child processes for a particular parent. ● Processes in a TASK_INTERRUPTIBLE or TASK_UNINTERRUPTIBLE state are subdivided into many classes, each of which corresponds to a specific event. In this case, the process state does not provide enough information to retrieve the process quickly, so it is necessary to introduce additional lists of processes. These are called wait queues. 3.2.4.1 Wait queues Wait queues have several uses in the kernel, particularly for interrupt handling, process synchronization, and timing. Because these topics are discussed in later chapters, we'll just say here that a process must often wait for some event to occur, such as for a disk operation to terminate, a system resource to be released, or a fixed interval of time to elapse. Wait queues implement conditional waits on events: a process wishing to wait for a specific event places itself in the proper wait queue and relinquishes control. Therefore, a wait queue represents a set of sleeping processes, which are woekn up by the kernel when some condition becomes true. Wait queues are implemented as doubly linked lists whose elements include pointers to process descriptors. Each wait queue is identified by a wait queue head, a data structure of type wait_queue_head_t: struct _ _wait_queue_head { spinlock_t lock; struct list_head task_list; }; typedef struct _ _wait_queue_head wait_queue_head_t; Since wait queues are modified by interrupt handlers as well by major kernel functions, the doubly linked lists must be protected from concurrent accesses, which could induce unpredictable results (see Chapter 5). Synchronization is achieved by the lock spin lock in the wait queue head. Elements of a wait queue list are of type wait_queue_t: struct _ _wait_queue { unsigned int flags; struct task_struct * task; struct list_head task_list; }; typedef struct _ _wait_queue wait_queue_t; Each element in the wait queue list represents a sleeping process, which is waiting for some event to occur; its descriptor address is stored in the task field. However, it is not always convenient to wake up all sleeping processes in a wait queue. For instance, if two or more processes are waiting for exclusive access to some resource to be released, it makes sense to wake up just one process in the wait queue. This process takes the resource, while the other processes continue to sleep. (This avoids a problem known as the "thundering herd," with which multiple processes are awoken only to race for a resource that can be accessed by one of them, and the result is that remaining processes must once more be put back to sleep.) Thus, there are two kinds of sleeping processes: exclusive processes (denoted by the value 1 in the flags field of the corresponding wait queue element) are selectively woken up by the kernel, while nonexclusive processes (denoted by the value 0 in flags) are always woken up by the kernel when the event occurs. A process waiting for a resource that can be granted to just one process at a time is a typical exclusive process. Processes waiting for an event like the termination of a disk operation are nonexclusive. 3.2.4.2 Handling wait queues The add_wait_queue( ) function inserts a nonexclusive process in the first position of a wait queue list. The add_wait_queue_exclusive( ) function inserts an exclusive process in the last position of a wait queue list. The remove_wait_queue( ) function removes a process from a wait queue list. The waitqueue_active( ) function checks whether a given wait queue list is empty. A new wait queue may be defined by using the DECLARE_WAIT_QUEUE_HEAD(name) macro, which statically declares and initializes a new wait queue head variable called name. The init_waitqueue_head( ) function may be used to initialize a wait queue head variable that was allocated dynamically. A process wishing to wait for a specific condition can invoke any of the functions shown in the following list. ● The sleep_on( ) function operates on the current process: void sleep_on(wait_queue_head_t *q) { unsigned long flags; wait_queue_t wait; wait.flags = 0; wait.task = current; current->state = TASK_UNINTERRUPTIBLE; add_wait_queue(q, &wait); schedule( ); remove_wait_queue(q, &wait); } The function sets the state of the current process to TASK_UNINTERRUPTIBLE and inserts it into the specified wait queue. Then it invokes the scheduler, which resumes the execution of another process. When the sleeping process is woken, the scheduler resumes execution of the sleep_on( ) function, which removes the process from the wait queue. ● The interruptible_sleep_on( ) is identical to sleep_on( ), except that it sets the state of the current process to TASK_INTERRUPTIBLE instead of setting it to TASK_UNINTERRUPTIBLE so that the process can also be woken up by receiving a signal. ● The sleep_on_timeout( ) and interruptible_sleep_on_timeout( ) functions are similar to the previous ones, but they also allow the caller to define a time interval after which the process will be woken up by the kernel. To do this, they invoke the schedule_timeout( ) function instead of schedule( ) (see Section 6.6.2). ● The wait_event and wait_event_interruptible macros, introduced in Linux 2.4, put the calling process to sleep on a wait queue until a given condition is verified. For instance, the wait_event_interruptible(wq,condition) macro essentially yields the following fragment (we have omitted the code related to signal handling and return values on purpose): if (!(condition)) { wait_queue_t _ _wait; init_waitqueue_entry(&_ _wait, current); add_wait_queue(&wq, &_ _wait); for (;;) { set_current_state(TASK_INTERRUPTIBLE); if (condition) break; schedule(); } current->state = TASK_RUNNING; remove_wait_queue(&wq, &_ _wait); } These macros should be used instead of the older sleep_on( ) and interruptible_sleep_on( ), because the latter functions cannot test a condition and atomically put the process to sleep when the condition is not verified and are thus a well-known source of race conditions. Notice that any process put to sleep by one of the above functions or macros is nonexclusive. Whenever the kernel wants to insert an exclusive process into a wait queue, it invokes add_wait_queue_exclusive( ) directly. Processes inserted in a wait queue enter the TASK_RUNNING state by means of one of the following macros: wake_up, wake_up_nr, wake_up_all, wake_up_sync, wake_up_sync_nr, wake_up_interruptible, wake_up_interruptible_nr, wake_up_interruptible_all, wake_up_interruptible_sync, and wake_up_interruptible_sync_nr. We can understand what each of these ten macros does from its name: ● All macros take into consideration sleeping processes in TASK_INTERRUPTIBLE state; if the macro name does not include the string "interruptible," sleeping processes in TASK_UNINTERRUPTIBLE state are also considered. ● All macros wake all nonexclusive processes having the required state (see the previous bullet item). ● The macros whose name include the string "nr" wake a given number of exclusive processes having the required state; this number is a parameter of the macro. The macros whose name include the string "all" wake all exclusive processes having the required state. Finally, the macros whose names don't include "nr" or "all" wake exactly one exclusive process that has the required state. ● The macros whose names don't include the string "sync" check whether the priority of the woken processes is higher than that of the processes currently running in the systems and invoke schedule( ) if necessary. These checks are not made by the macros whose names include the string "sync." For instance, the wake_up macro is equivalent to the following code fragment: void wake_up(wait_queue_head_t *q) { struct list_head *tmp; wait_queue_t *curr; list_for_each(tmp, &q->task_list) { curr = list_entry(tmp, wait_queue_t, task_list); wake_up_process(curr->task); if (curr->flags) break; } } The list_for_each macro scans all items in the doubly linked list of q. For each item, the list_entry macro computes the address of the correspondent wait_queue_t variable. The task field of this variable stores the pointer to the process descriptor, which is then passed to the wake_up_process( ) function. If the woken process is exclusive, the loop terminates. Since all nonexclusive processes are always at the beginning of the doubly linked list and all exclusive processes are at the end, the function always waken the nonexclusive processes and then wakes one exclusive process, if any exists.[3] Notice that awoken processes are not removed from the wait queue. A process could be awoken while the wait condition is still false; in this case, the process may suspend itself again in the same wait queue. [3] By the way, it is rather uncommon that a wait queue includes both exclusive and nonexclusive processes. 3.2.5 Process Resource Limits Each process has an associated set of resource limits, which specify the amount of system resources it can use. These limits keep a user from overwhelming the system (its CPU, disk space, and so on). Linux recognizes the following resource limits: RLIMIT_AS The maximum size of process address space, in bytes. The kernel checks this value when the process uses malloc( ) or a related function to enlarge its address space (see Section 8.1). RLIMIT_CORE The maximum core dump file size, in bytes. The kernel checks this value when a process is aborted, before creating a core file in the current directory of the process (see Section 10.1.1). If the limit is 0, the kernel won't create the file. RLIMIT_CPU The maximum CPU time for the process, in seconds. If the process exceeds the limit, the kernel sends it a SIGXCPU signal, and then, if the process doesn't terminate, a SIGKILL signal (see Chapter 10). RLIMIT_DATA The maximum heap size, in bytes. The kernel checks this value before expanding the heap of the process (see Section 8.6). RLIMIT_FSIZE The maximum file size allowed, in bytes. If the process tries to enlarge a file to a size greater than this value, the kernel sends it a SIGXFSZ signal. RLIMIT_LOCKS The maximum number of file locks. The kernel checks this value when the process enforces a lock on a file (see Section 12.7). RLIMIT_MEMLOCK The maximum size of nonswappable memory, in bytes. The kernel checks this value when the process tries to lock a page frame in memory using the mlock( ) or mlockall( ) system calls (see Section 8.3.4). RLIMIT_NOFILE The maximum number of open file descriptors. The kernel checks this value when opening a new file or duplicating a file descriptor (see Chapter 12). RLIMIT_NPROC The maximum number of processes that the user can own (see Section 3.4.1 later in this chapter). RLIMIT_RSS The maximum number of page frames owned by the process. The kernel checks this value when the process uses malloc( ) or a related function to enlarge its address space (see Section 8.1). RLIMIT_STACK The maximum stack size, in bytes. The kernel checks this value before expanding the User Mode stack of the process (see Section 8.4). The resource limits are stored in the rlim field of the process descriptor. The field is an array of elements of type struct rlimit, one for each resource limit: struct rlimit { unsigned long rlim_cur; unsigned long rlim_max; }; The rlim_cur field is the current resource limit for the resource. For example, current- >rlim[RLIMIT_CPU].rlim_cur represents the current limit on the CPU time of the running process. The rlim_max field is the maximum allowed value for the resource limit. By using the getrlimit( ) and setrlimit( ) system calls, a user can always increase the rlim_cur limit of some resource up to rlim_max. However, only the superuser (or, more precisely, a user who has the CAP_SYS_RESOURCE capability) can increase the rlim_max field or set the rlim_cur field to a value greater than the corresponding rlim_max field. Most resource limits contain the value RLIM_INFINITY (0xffffffff), which means that no user limit is imposed on the corresponding resource (of course, real limits exist due to kernel design restrictions, available RAM, available space on disk, etc.). However, the system administrator may choose to impose stronger limits on some resources. Whenever a user logs into the system, the kernel creates a process owned by the superuser, which can invoke setrlimit( ) to decrease the rlim_max and rlim_cur fields for a resource. The same process later executes a login shell and becomes owned by the user. Each new process created by the user inherits the content of the rlim array from its parent, and therefore the user cannot override the limits enforced by the system. I l@ve RuBoard I l@ve RuBoard 3.3 Process Switch To control the execution of processes, the kernel must be able to suspend the execution of the process running on the CPU and resume the execution of some other process previously suspended. This activity goes variously by the names process switch, task switch, or context switch. The next sections describe the elements of process switching in Linux. 3.3.1 Hardware Context While each process can have its own address space, all processes have to share the CPU registers. So before resuming the execution of a process, the kernel must ensure that each such register is loaded with the value it had when the process was suspended. The set of data that must be loaded into the registers before the process resumes its execution on the CPU is called the hardware context. The hardware context is a subset of the process execution context, which includes all information needed for the process execution. In Linux, a part of the hardware context of a process is stored in the process descriptor, while the remaining part is saved in the Kernel Mode stack. In the description that follows, we will assume the prev local variable refers to the process descriptor of the process being switched out and next refers to the one being switched in to replace it. We can thus define a process switch as the activity consisting of saving the hardware context of prev and replacing it with the hardware context of next. Since process switches occur quite often, it is important to minimize the time spent in saving and loading hardware contexts. Old versions of Linux took advantage of the hardware support offered by the Intel architecture and performed a process switch through a far jmp instruction[4] to the selector of the Task State Segment Descriptor of the next process. While executing the instruction, the CPU performs a hardware context switch by automatically saving the old hardware context and loading a new one. But Linux 2.4 uses software to perform a process switch for the following reasons: [4] far jmp instructions modify both the cs and eip registers, while simple jmp instructions modify only eip. ● Step-by-step switching performed through a sequence of mov instructions allows better control over the validity of the data being loaded. In particular, it is possible to check the values of segmentation registers. This type of checking is not possible when using a single far jmp instruction. ● The amount of time required by the old approach and the new approach is about the same. However, it is not possible to optimize a hardware context switch, while there might be room for improving the current switching code. Process switching occurs only in Kernel Mode. The contents of all registers used by a process in User Mode have already been saved before performing process switching (see Chapter 4). This includes the contents of the ss and esp pair that specifies the User Mode stack pointer address. 3.3.2 Task State Segment The 80 x 86 architecture includes a specific segment type called the Task State Segment (TSS), to store hardware contexts. Although Linux doesn't use hardware context switches, it is nonetheless forced to set up a TSS for each distinct CPU in the system. This is done for two main reasons: ● When an 80 x 86 CPU switches from User Mode to Kernel Mode, it fetches the address of the Kernel Mode stack from the TSS (see Chapter 4). ● When a User Mode process attempts to access an I/O port by means of an in or out instruction, the CPU may need to access an I/O Permission Bitmap stored in the TSS to verify whether the process is allowed to address the port. More precisely, when a process executes an in or out I/O instruction in User Mode, the control unit performs the following operations: 1. It checks the 2-bit IOPL field in the eflags register. If it is set to 3, the control unit executes the I/O instructions. Otherwise, it performs the next check. 2. It accesses the tr register to determine the current TSS, and thus the proper I/O Permission Bitmap. 3. It checks the bit of the I/O Permission Bitmap corresponding to the I/O port specified in the I/O instruction. If it is cleared, the instruction is executed; otherwise, the control unit raises a "General protection error" exception. The tss_struct structure describes the format of the TSS. As already mentioned in Chapter 2, the init_tss array stores one TSS for each different CPU on the system. At each process switch, the kernel updates some fields of the TSS so that the corresponding CPU's control unit may safely retrieve the information it needs. Each TSS has its own 8-byte Task State Segment Descriptor (TSSD). This Descriptor includes a 32-bit Base field that points to the TSS starting address and a 20-bit Limit field. The S flag of a TSSD is cleared to denote the fact that the corresponding TSS is a System Segment. The Type field is set to either 9 or 11 to denote that the segment is actually a TSS. In the Intel's original design, each process in the system should refer to its own TSS; the second least significant bit of the Type field is called the Busy bit; it is set to 1 if the process is being executed by a CPU, and to 0 otherwise. In Linux design, there is just one TSS for each CPU, so the Busy bit is always set to 1. The TSSDs created by Linux are stored in the Global Descriptor Table (GDT), whose base address is stored in the gdtr register of each CPU. The tr register of each CPU contains the TSSD Selector of the corresponding TSS. The register also includes two hidden, nonprogrammable fields: the Base and Limit fields of the TSSD. In this way, the processor can address the TSS directly without having to retrieve the TSS address from the GDT. 3.3.2.1 The thread field At every process switch, the hardware context of the process being replaced must be saved somewhere. It cannot be saved on the TSS, as in the original Intel design, because we cannot make assumptions about when the process being replaced will resume execution and what CPU will execute it again. Thus, each process descriptor includes a field called thread of type thread_struct, in which the kernel saves the hardware context whenever the process is being switched out. As we shall see later, this data structure includes fields for most of the CPU registers, such as the general-purpose registers, the floating point registers, and so on. 3.3.3 Performing the Process Switch A process switch may occur at just one well-defined point: the schedule( ) function (discussed at length in Chapter 11). Here, we are only concerned with how the kernel performs a process switch. Essentially, every process switch consists of two steps: 1. Switching the Page Global Directory to install a new address space; we'll describe this step in Chapter 8. 2. Switching the Kernel Mode stack and the hardware context, which provides all the information needed by the kernel to execute the new process, including the CPU registers. Again, we assume that prev points to the descriptor of the process being replaced, and next to the descriptor of the process being activated. As we shall see in Chapter 11, prev and next are local variables of the schedule( ) function. The second step of the process switch is performed by the switch_to macro. It is one of the most hardware-dependent routines of the kernel, and it takes some effort to understand what it does. First of all, the macro has three parameters called prev, next, and last. The actual invocation of the macro in schedule( ) is: switch_to(prev, next, prev); You might easily guess the role of prev and next — they are just placeholders for the local variables prev and next — but what about the third parameter last? Well, the point is that in any process switch, three processes are involved, not just two. Suppose the kernel decides to switch off process A and to activate process B. In the schedule( ) function, prev points to A's descriptor and next points to B's descriptor. As soon as the switch_to macro deactivates A, the execution flow of A freezes. Later, when the kernel wants to reactivate A, it must switch off another process C (in general, this is different from B) by executing another switch_to macro with prev pointing to C and next pointing to A. When A resumes its execution flow, it finds its old Kernel Mode stack, so the prev local variable points to A's descriptor and next points to B's descriptor. The kernel, which is now executing on behalf of process A, has lost any reference to C. The last parameter of the switch_to macro reinserts the address of C's descriptor into the prev local variable. The mechanism exploits the state of registers during function calls. The first prev parameter corresponds to a CPU register, which is loaded with the content of the prev local variable when the macro starts. When the macro ends, it writes the content of the same register in the last parameter — namely, in the prev local variable. However, the CPU register doesn't change across the process switch, so prev receives the address of C's descriptor (as we shall see in Chapter 11, the scheduler checks whether C should be readily executed on another CPU). Here is a description of what the switch_to macro does on an 80 x 86 microprocessor: 1. Saves the values of prev and next in the eax and edx registers, respectively: movl prev,%eax movl next,%edx The eax and edx registers correspond to the prev and next parameters of the macro. 2. Saves another copy of prev in the ebx register; ebx corresponds to the last parameter of the macro: movl %eax,%ebx 3. Saves the contents of the esi, edi, and ebp registers in the prev Kernel Mode stack. They must be saved because the compiler assumes that they will stay unchanged until the end of switch_to: pushl %esi pushl %edi pushl %ebp 4. Saves the content of esp in prev->thread.esp so that the field points to the top of the prev Kernel Mode stack: movl %esp, 616(%eax) The 616(%eax) operand identifies the memory cell whose address is the contents of eax plus 616. 5. Loads next->thread.esp in esp. From now on, the kernel operates on the Kernel Mode stack of next, so this instruction performs the actual process switch from prev to next. Since the address of a process descriptor is closely related to that of the Kernel Mode stack (as explained in Section 3.2.2 earlier in this chapter), changing the kernel stack means changing the current process: movl 616(%edx), %esp 6. Saves the address labeled 1 (shown later in this section) in prev->thread.eip. When the process being replaced resumes its execution, the process executes the instruction labeled as 1: movl $1f, 612(%eax) 7. On the Kernel Mode stack of next, the macro pushes the next->thread.eip value, which, in most cases, is the address labeled 1: pushl 612(%edx) 8. Jumps to the _ _switch_to( ) C function: jmp _ _switch_to This function acts on the prev and next parameters that denote the former process and the new process. This function call is different from the average function call, though, because _ _switch_to( ) takes the prev and next parameters from the eax and edx (where we saw they were stored), not from the stack like most functions. To force the function to go to the registers for its parameters, the kernel uses the _ _attribute_ _ and regparm keywords, which are nonstandard extensions of the C language implemented by the gcc compiler. The _ _switch_to( ) function is declared in the include /asm-i386 /system.h header file as follows: _ _switch_to(struct task_struct *prev, struct task_struct *next) _ _attribute_ _(regparm(3)) The _ _switch_to( ) function completes the process switch started by the switch_to( ) macro. It includes extended inline assembly language code that makes for rather complex reading because the code refers to registers by means of special symbols: a. Executes the code yielded by the unlazy_fpu( ) macro (see Section 3.3.4 later in this chapter) to optionally save the contents of the FPU, MMX, and XMM registers. As we shall see, there is no need to load the corresponding registers of next while performing the context switch: unlazy_fpu(prev); b. Loads next->esp0 in the esp0 field of the TSS relative to the current CPU so that any future privilege level change from User Mode to Kernel Mode automatically forces this address into the esp register: init_tss[smp_processor_id( )].esp0 = next->thread.esp0; The smp_processor_id( ) macro yields the index of the executing CPU. c. Stores the contents of the fs and gs segmentation registers in prev->thread.fs and prev->thread.gs, respectively; the corresponding assembly language instructions are: movl %fs,620(%esi) movl %gs,624(%esi) The esi register points to the prev->thread structure. d. Loads the fs and gs segment registers with the values contained in next->thread.fs and next->thread.gs, respectively. This step logically complements the actions performed in the previous step. The corresponding assembly language instructions are: movl 12(%ebx),%fs movl 17(%ebx),%gs The ebx register points to the next->thread structure. The code is actually more intricate, as an exception might be raised by the CPU when it detects an invalid segment register value. The code takes this possibility into account by adopting a "fix-up" approach (see Section 9.2.6). e. Loads six debug registers[5] with the contents of the next->thread.debugreg array. [5] The 80 x 86 debug registers allow a process to be monitored by the hardware. Up to four breakpoint areas may be defined. Whenever a monitored process issues a linear address included in one of the breakpoint areas, an exception occurs. This is done only if next was using the debug registers when it was suspended (that is, field next->thread.debugreg[7] is not 0). As we shall see in Chapter 20, these registers are modified only by writing in the TSS, so there is no need to save the corresponding registers of prev: if (next->thread.debugreg[7]){ loaddebug(&next->thread, 0); loaddebug(&next->thread, 1); loaddebug(&next->thread, 2); loaddebug(&next->thread, 3); /* no 4 and 5 */ loaddebug(&next->thread, 6); loaddebug(&next->thread, 7); } 9. Updates the I/O bitmap in the TSS, if necessary. This must be done when either next or prev have their own customized I/O Permission Bitmap: if (next->thread.ioperm) { memcpy(init_tss[smp_processor_id( )].io_bitmap, next->thread.io_bitmap, 128)); init_tss[smp_processor_id( )].bitmap = 104; } else if (prev->thread.ioperm) init_tss[smp_processor_id( )].bitmap = 0x8000; The customized I/O Permission Bitmap of a process is stored in a buffer pointed to by the thread.io_bitmap field of the process descriptor. If next has a customized bitmap, it is copied into the io_bitmap field of the TSS. Otherwise, if next doesn't have it, the kernel checks whether prev defined such a bitmap. In this case, the bitmap must be invalidated. 10. Terminates. Like any other function, _ _switch_to( ) ends by means of a ret assembly language instruction, which loads the eip program counter with the return address stored into the stack. However, the _ _switch_to( ) function has been invoked simply by jumping into it. Therefore the ret assembly language instruction finds on the stack the address of the instruction shown in the following item and labeled 1, which was pushed by the switch_to macro. If next was never suspended before because it is being executed for the first time, the function finds the starting address of the ret_from_fork( ) function (see Section 3.4.1 later in this chapter). ● Includes a few instructions that restore the contents of the esi, edi, and ebp registers. The first of these three instructions is labeled 1: 1: popl %ebp popl %edi popl %esi Notice how these pop instructions refer to the kernel stack of the prev process. They will be executed when the scheduler selects prev as the new process to be executed on the CPU, thus invoking switch_to with prev as the second parameter. Therefore, the esp register points to the prev's Kernel Mode stack. ● Copies the content of the ebx register (corresponding to the last parameter of the switch_to macro) into the prev local variable: movl %ebx,prev As discussed earlier, the ebx register points to the descriptor of the process that has just been replaced. 3.3.4 Saving the FPU, MMX, and XMM Registers Starting with the Intel 80486, the arithmetic floating-point unit (FPU) has been integrated into the CPU. The name mathematical coprocessor continues to be used in memory of the days when floating-point computations were executed by an expensive special-purpose chip. To maintain compatibility with older models, however, floating-point arithmetic functions are performed with ESCAPE instructions, which are instructions with a prefix byte ranging between 0xd8 and 0xdf. These instructions act on the set of floating point registers included in the CPU. Clearly, if a process is using ESCAPE instructions, the contents of the floating point registers belong to its hardware context. In later Pentium models, Intel introduced a new set of assembly language instructions into its microprocessors. They are called MMX instructions and are supposed to speed up the execution of multimedia applications. MMX instructions act on the floating point registers of the FPU. The obvious disadvantage of this architectural choice is that programmers cannot mix floating-point instructions and MMX instructions. The advantage is that operating system designers can ignore the new instruction set, since the same facility of the task-switching code for saving the state of the floating-point unit can also be relied upon to save the MMX state. MMX instructions speed up multimedia applications because they introduce a single-instruction multiple- data (SIMD) pipeline inside the processor. The Pentium III model extends such SIMD capability: it introduces the SSE extensions (Streaming SIMD Extensions), which adds facilities for handling floating- point values contained in eight 128-bit registers (the XMM registers). Such registers do not overlap with the FPU and MMX registers, so SSE and FPU/MMX instructions may be freely mixed. The Pentium 4 model introduces yet another feature: the SSE2 extensions, which is basically an extension of SSE supporting higher-precision floating-point values. SSE2 uses the same set of XMM registers as SSE. The 80 x 86 microprocessors do not automatically save the FPU, MMX, and XMM registers in the TSS. However, they include some hardware support that enables kernels to save these registers only when needed. The hardware support consists of a TS (Task-Switching) flag in the cr0 register, which obeys the following rules: ● Every time a hardware context switch is performed, the TS flag is set. ● Every time an ESCAPE, MMX, SSE, or SSE2 instruction is executed when the TS flag is set, the control unit raises a "Device not available" exception (see Chapter 4). The TS flag allows the kernel to save and restore the FPU, MMX, and XMM registers only when really needed. To illustrate how it works, suppose that a process A is using the mathematical coprocessor. When a context switch occurs, the kernel sets the TS flag and saves the floating point registers into the TSS of process A. If the new process B does not use the mathematical coprocessor, the kernel won't need to restore the contents of the floating point registers. But as soon as B tries to execute an ESCAPE or MMX instruction, the CPU raises a "Device not available" exception, and the corresponding handler loads the floating point registers with the values saved in the TSS of process B. Let's now describe the data structures introduced to handle selective loading of the FPU, MMX, and XMM registers. They are stored in the thread.i387 subfield of the process descriptor, whose format is described by the i387_union union: union i387_union { struct i387_fsave_struct fsave; struct i387_fxsave_struct fxsave; struct i387_soft_struct soft; }; As you see, the field may store just one of three different types of data structures. The i387_soft_struct type is used by CPU models without a mathematical coprocessor; the Linux kernel still supports these old chips by emulating the coprocessor via software. We don't discuss this legacy case further, however. The i387_fsave_struct type is used by CPU models with a mathematical coprocessor and, optionally, a MMX unit. Finally, the i387_fxsave_struct type is used by CPU models featuring SSE and SSE2 extensions. The process descriptor includes two additional flags: ● The PF_USEDFPU flag, which is included in the flags field. It specifies whether the process used the FPU, MMX, or XMM registers in the current execution run. ● The used_math field. This flag specifies whether the contents of the thread.i387 subfield are significant. The flag is cleared (not significant) in two cases, shown in the following list. ❍ When the process starts executing a new program by invoking an execve( ) system call (see Chapter 20). Since control will never return to the former program, the data currently stored in thread.i387 is never used again. ❍ When a process that was executing a program in User Mode starts executing a signal handler procedure (see Chapter 10). Since signal handlers are asynchronous with respect to the program execution flow, the floating point registers could be meaningless to the signal handler. However, the kernel saves the floating point registers in thread.i387 before starting the handler and restores them after the handler terminates. Therefore, a signal handler is allowed to use the mathematical coprocessor, but it cannot carry on a floating-point computation started during the normal program execution flow. As stated earlier, the _ _switch_to( ) function executes the unlazy_fpu macro, passing the process descriptor of the process being replaced as an argument. The macro checks the value of the PF_USEDFPU flags of prev. If the flag is set, prev has used a FPU, MMX, SSE, or SSE2 instructions in this run of execution; therefore, the kernel must save the relative hardware context: if (prev->flags & PF_USEDFPU) save_init_fpu(prev); The save_init_fpu( ) function, in turn, executes the following operations: 1. Dumps the contents of the FPU registers in the process descriptor of prev and then re-initializes the FPU. If the CPU uses SSE/SSE2 extensions, it also dumps the contents of the XMM registers and re-initialize the SSE/SSE2 unit. A couple of powerful assembly language instructions take care of everything, either: asm volatile( "fxsave %0 ; fnclex" : "=m" (tsk->thread.i387.fxsave) ); if the CPU uses SSE/SSE2 extensions, or otherwise: asm volatile( "fnsave %0 ; fwait" : "=m" (tsk->thread.i387.fsave) ); 2. Resets the PF_USEDFPU flag of prev: prev->flags &= ~PF_USEDFPU; 3. Sets the TS flag of cr0 by means of the stts( ) macro, which in practice yields the following assembly language instructions: movl %cr0, %eax orl $8,%eax movl %eax, %cr0 The contents of the floating point registers are not restored right after a process resumes execution. However, the TS flag of cr0 has been set by unlazy_fpu( ). Thus, the first time the process tries to execute an ESCAPE, MMX, or SSE/SSE2 instruction, the control unit raises a "Device not available" exception, and the kernel (more precisely, the exception handler involved by the exception) runs the math_state_restore( ) function: void math_state_restore( ) { asm("clts"); /* clear the TS flag of cr0 */ if (current->used_math) { restore_fpu(current); } else { /* initialize the FPU unit */ asm("fninit"); /* and also the SSE/SSE2 unit, if present */ if ( cpu_has_xmm ) load_mxcsr(0x1f80); current->used_math = 1; } current->flags |= PF_USEDFPU; } Since the process is executing an FPU, MMX, or SSE/SSE2 instruction, this function sets the PF_USEDFPU flag. Moreover, the function clears the TS flags of cr0 so that further FPU, MMX, or SSE/SSE2 instructions executed by the process won't trigger the "Device is not available" exception. If the data stored in the thread.i387 field is valid, the restore_fpu( ) function loads the registers with the proper values. To do this, either the fxrstor or the frstor assembly language instructions are used, depending on whether the CPU supports SSE/SSE2 extensions. Otherwise, if the data stored in the thread.i387 field is not valid, the FPU/MMX unit is re-initialized and all its registers are cleared. To re-initialize the SSE/SSE2 unit, it is sufficient to load a value in a XMM register. I l@ve RuBoard I l@ve RuBoard 3.4 Creating Processes Unix operating systems rely heavily on process creation to satisfy user requests. For example, the shell creates a new process that executes another copy of the shell whenever the user enters a command. Traditional Unix systems treat all processes in the same way: resources owned by the parent process are duplicated in the child process. This approach makes process creation very slow and inefficient, since it requires copying the entire address space of the parent process. The child process rarely needs to read or modify all the resources inherited from the parent; in many cases, it issues an immediate execve( ) and wipes out the address space that was so carefully copied. Modern Unix kernels solve this problem by introducing three different mechanisms: ● The Copy On Write technique allows both the parent and the child to read the same physical pages. Whenever either one tries to write on a physical page, the kernel copies its contents into a new physical page that is assigned to the writing process. The implementation of this technique in Linux is fully explained in Chapter 8. ● Lightweight processes allow both the parent and the child to share many per-process kernel data structures, such as the paging tables (and therefore the entire User Mode address space), the open file tables, and the signal dispositions. ● The vfork( ) system call creates a process that shares the memory address space of its parent. To prevent the parent from overwriting data needed by the child, the parent's execution is blocked until the child exits or executes a new program. We'll learn more about the vfork( ) system call in the following section. 3.4.1 The clone( ), fork( ), and vfork( ) System Calls Lightweight processes are created in Linux by using a function named clone( ), which uses four parameters: fn Specifies a function to be executed by the new process; when the function returns, the child terminates. The function returns an integer, which represents the exit code for the child process. arg Points to data passed to the fn( ) function. flags Miscellaneous information. The low byte specifies the signal number to be sent to the parent process when the child terminates; the SIGCHLD signal is generally selected. The remaining three bytes encode a group of clone flags, which specify the resources to be shared between the parent and the child process as follows: CLONE_VM Shares the memory descriptor and all Page Tables (see Chapter 8). CLONE_FS Shares the table that identifies the root directory and the current working directory, as well as the value of the bitmask used to mask the initial file permissions of a new file (the so-called file umask). CLONE_FILES Shares the table that identifies the open files (see Chapter 12). CLONE_PARENT Sets the parent of the child (p_pptr and p_opptr fields in the process descriptor) to the parent of the calling process. CLONE_PID Shares the PID.[6] [6] As we shall see later, the CLONE_PID flag can be used only by a process having a PID of 0; in a uniprocessor system, no two lightweight processes have the same PID. CLONE_PTRACE If a ptrace( ) system call is causing the parent process to be traced, the child will also be traced. CLONE_SIGHAND Shares the table that identifies the signal handlers (see Chapter 10). CLONE_THREAD Inserts the child into the same thread group of the parent, and the child's tgid field is set accordingly. If this flag is true, it implicitly enforces CLONE_PARENT. CLONE_SIGNAL Equivalent to setting both CLONE_SIGHAND and CLONE_THREAD, so that it is possible to send a signal to all threads of a multithreaded application. CLONE_VFORK Used for the vfork( ) system call (see later in this section). child_stack Specifies the User Mode stack pointer to be assigned to the esp register of the child process. If it is equal to 0, the kernel assigns the current parent stack pointer to the child. Therefore, the parent and child temporarily share the same User Mode stack. But thanks to the Copy On Write mechanism, they usually get separate copies of the User Mode stack as soon as one tries to change the stack. However, this parameter must have a non-null value if the child process shares the same address space as the parent. clone( ) is actually a wrapper function defined in the C library (see Section 9.1), which in turn uses a clone( ) system call hidden to the programmer. This system call receives only the flags and child_stack parameters; the new process always starts its execution from the instruction following the system call invocation. When the system call returns to the clone( ) function, it determines whether it is in the parent or the child and forces the child to execute the fn( ) function. The traditional fork( ) system call is implemented by Linux as a clone( ) system call whose flags parameter specifies both a SIGCHLD signal and all the clone flags cleared, and whose child_stack parameter is 0. The vfork( ) system call, described in the previous section, is implemented by Linux as a clone( ) system call whose first parameter specifies both a SIGCHLD signal and the flags CLONE_VM and CLONE_VFORK, and whose second parameter is equal to 0. When either a clone( ), fork( ), or vfork( ) system call is issued, the kernel invokes the do_fork( ) function, which executes the following steps: 1. If the CLONE_PID flag is specified, the do_fork( ) function checks whether the PID of the parent process is not 0; if so, it returns an error code. Only the swapper process is allowed to set CLONE_PID; this is required when initializing a multiprocessor system. 2. The alloc_task_struct( ) function is invoked to get a new 8 KB union task_union memory area to store the process descriptor and the Kernel Mode stack of the new process. 3. The function follows the current pointer to obtain the parent process descriptor and copies it into the new process descriptor in the memory area just allocated. 4. A few checks occur to make sure the user has the resources necessary to start a new process. First, the function checks whether current- >rlim[RLIMIT_NPROC].rlim_cur is smaller than or equal to the current number of processes owned by the user. If so, an error code is returned, unless the process has root privileges. The function gets the current number of processes owned by the user from a per-user data structure named user_struct. This data structure can be found through a pointer in the user field of the process descriptor. 5. The function checks that the number of processes is smaller than the value of the max_threads variable. The initial value of this variable depends on the amount of RAM in the system. The general rule is that the space taken by all process descriptors and Kernel Mode stacks cannot exceed 1/8 of the physical memory. However, the system administrator may change this value by writing in the /proc/sys/kernel/threads-max file. 6. If the parent process uses any kernel modules, the function increments the corresponding reference counters. As we shall see in Appendix B, each kernel module has its own reference counter, which ensures that the module will not be unloaded while it is being used. 7. The function then updates some of the flags included in the flags field that have been copied from the parent process: a. It clears the PF_SUPERPRIV flag, which indicates whether the process has used any of its superuser privileges. b. It clears the PF_USEDFPU flag. c. It sets the PF_FORKNOEXEC flag, which indicates that the child process has not yet issued an execve( ) system call. 8. Now the function has taken almost everything that it can use from the parent process; the rest of its activities focus on setting up new resources in the child and letting the kernel know that this new process has been born. First, the function invokes the get_pid( ) function to obtain a new PID, which will be assigned to the child process (unless the CLONE_PID flag is set). 9. The function then updates all the process descriptor fields that cannot be inherited from the parent process, such as the fields that specify the process parenthood relationships. 10. Unless specified differently by the flags parameter, it invokes copy_files( ), copy_fs( ), copy_sighand( ), and copy_mm( ) to create new data structures and copy into them the values of the corresponding parent process data structures. 11. The do_fork( ) function invokes copy_thread( ) to initialize the Kernel Mode stack of the child process with the values contained in the CPU registers when the clone( ) call was issued (these values have been saved in the Kernel Mode stack of the parent, as described in Chapter 9). However, the function forces the value 0 into the field corresponding to the eax register. The thread.esp field in the descriptor of the child process is initialized with the base address of the child's Kernel Mode stack, and the address of an assembly language function (ret_from_fork( )) is stored in the thread.eip field. The copy_thread( ) function also invokes unlazy_fpu( ) on the parent and duplicates the contents of the thread.i387 field. 12. If either CLONE_THREAD or CLONE_PARENT is set, the function copies the value of the p_opptr and p_pptr fields of the parent into the corresponding fields of the child. The parent of the child thus appears as the parent of the current process. Otherwise, the function stores the process descriptor address of current into the p_opptr and p_pptr fields of the child. 13. If the CLONE_PTRACE flag is not set, the function sets the ptrace field in the child process descriptor to 0. This field stores a few flags used when a process is being traced by another process. Even if the current process is being traced, the child will not. 14. Conversely, if the CLONE_PTRACE flag is set, the function checks whether the parent process is being traced because in this case, the child should be traced too. Therefore, if PT_PTRACED is set in current->ptrace, the function copies the current->p_pptr field into the corresponding field of the child. 15. The do_fork( ) function checks the value of CLONE_THREAD. If the flag is set, the function inserts the child in the thread group of the parent and copies in the tgid field the value of the parent's tgid; otherwise, the function sets the tgid field to the value of the pid field. 16. The function uses the SET_LINKS macro to insert the new process descriptor in the process list. 17. The function invokes hash_pid( ) to insert the new process descriptor in the pidhash hash table. 18. The function increments the values of nr_threads and current->user- >processes. 19. If the child is being traced, the function sends a SIGSTOP signal to it so that the debugger has a chance to look at it before it starts the execution. 20. It invokes wake_up_process( ) to set the state field of the child process descriptor to TASK_RUNNING and to insert the child in the runqueue list. 21. If the CLONE_VFORK flag is specified, the function inserts the parent process in a wait queue and suspends it until the child releases its memory address space (that is, until the child either terminates or executes a new program). 22. The do_fork( ) function returns the PID of the child, which is eventually read by the parent process in User Mode. Now we have a complete child process in the runnable state. But it isn't actually running. It is up to the scheduler to decide when to give the CPU to this child. At some future process switch, the schedule bestows this favor on the child process by loading a few CPU registers with the values of the thread field of the child's process descriptor. In particular, esp is loaded with thread.esp (that is, with the address of child's Kernel Mode stack), and eip is loaded with the address of ret_from_fork( ). This assembly language function, in turn, invokes the ret_from_sys_call( ) function (see Chapter 9), which reloads all other registers with the values stored in the stack and forces the CPU back to User Mode. The new process then starts its execution right at the end of the fork( ), vfork( ), or clone( ) system call. The value returned by the system call is contained in eax: the value is 0 for the child and equal to the PID for the child's parent. The child process executes the same code as the parent, except that the fork returns a 0. The developer of the application can exploit this fact, in a manner familiar to Unix programmers, by inserting a conditional statement in the program based on the PID value that forces the child to behave differently from the parent process. 3.4.2 Kernel Threads Traditional Unix systems delegate some critical tasks to intermittently running processes, including flushing disk caches, swapping out unused page frames, servicing network connections, and so on. Indeed, it is not efficient to perform these tasks in strict linear fashion; both their functions and the end user processes get better responses if they are scheduled in the background. Since some of the system processes run only in Kernel Mode, modern operating systems delegate their functions to kernel threads, which are not encumbered with the unnecessary User Mode context. In Linux, kernel threads differ from regular processes in the following ways: ● Each kernel thread executes a single specific kernel C function, while regular processes execute kernel functions only through system calls. ● Kernel threads run only in Kernel Mode, while regular processes run alternatively in Kernel Mode and in User Mode. ● Since kernel threads run only in Kernel Mode, they use only linear addresses greater than PAGE_OFFSET. Regular processes, on the other hand, use all four gigabytes of linear addresses, in either User Mode or Kernel Mode. 3.4.2.1 Creating a kernel thread The kernel_thread( ) function creates a new kernel thread and can be executed only by another kernel thread. The function contains mostly inline assembly language code, but it is roughly equivalent to the following: int kernel_thread(int (*fn)(void *), void * arg, unsigned long flags) { int p; p = clone( 0, flags | CLONE_VM ); if ( p ) /* parent */ return p; else { /* child */ fn(arg); exit( ); } } 3.4.2.2 Process 0 The ancestor of all processes, called process 0 or, for historical reasons, the swapper process, is a kernel thread created from scratch during the initialization phase of Linux by the start_kernel( ) function (see Appendix A). This ancestor process uses the following data structures: ● A process descriptor and a Kernel Mode stack stored in the init_task_union variable. The init_task and init_stack macros yield the addresses of the process descriptor and the stack, respectively. ● The following tables, which the process descriptor points to: ❍ init_mm ❍ init_fs ❍ init_files ❍ init_signals The tables are initialized, respectively, by the following macros: ❍ INIT_MM ❍ INIT_FS ❍ INIT_FILES ❍ INIT_SIGNALS ● The master kernel Page Global Directory stored in swapper_pg_dir (see Section 2.5.5). The start_kernel( ) function initializes all the data structures needed by the kernel, enables interrupts, and creates another kernel thread, named process 1 (more commonly referred to as the init process): kernel_thread(init, NULL, CLONE_FS | CLONE_FILES | CLONE_SIGNAL); The newly created kernel thread has PID 1 and shares all per-process kernel data structures with process 0. Moreover, when selected from the scheduler, the init process starts executing the init( ) function. After having created the init process, process 0 executes the cpu_idle( ) function, which essentially consists of repeatedly executing the hlt assembly language instruction with the interrupts enabled (see Chapter 4). Process 0 is selected by the scheduler only when there are no other processes in the TASK_RUNNING state. 3.4.2.3 Process 1 The kernel thread created by process 0 executes the init( ) function, which in turn completes the initialization of the kernel. Then init( ) invokes the execve( ) system call to load the executable program init. As a result, the init kernel thread becomes a regular process having its own per-process kernel data structure (see Chapter 20). The init process stays alive until the system is shut down, since it creates and monitors the activity of all processes that implement the outer layers of the operating system. 3.4.2.4 Other kernel threads Linux uses many other kernel threads. Some of them are created in the initialization phase and run until shutdown; others are created "on demand," when the kernel must execute a task that is better performed in its own execution context. The most important kernel threads (beside process 0 and process 1) are: keventd Executes the tasks in the qt_context task queue (see Section 4.7.3). kapm Handles the events related to the Advanced Power Management (APM). kswapd Performs memory reclaiming, as described in Section 16.7.7. kflushd (also bdflush) Flushes "dirty" buffers to disk to reclaim memory, as described in Section 14.2.4. kupdated Flushes old "dirty" buffers to disk to reduce risks of filesystem inconsistencies, as described in Section 14.2.4. ksoftirqd Runs the tasklets (see section Section 4.7); there is one kernel thread for each CPU in the system. I l@ve RuBoard I l@ve RuBoard 3.5 Destroying Processes Most processes "die" in the sense that they terminate the execution of the code they were supposed to run. When this occurs, the kernel must be notified so that it can release the resources owned by the process; this includes memory, open files, and any other odds and ends that we will encounter in this book, such as semaphores. The usual way for a process to terminate is to invoke the exit( ) library function, which releases the resources allocated by the C library, executes each function registered by the programmer, and ends up invoking the _exit( ) system call. The exit( ) function may be inserted by the programmer explicitly. Additionally, the C compiler always inserts an exit( ) function call right after the last statement of the main( ) function. Alternatively, the kernel may force a process to die. This typically occurs when the process has received a signal that it cannot handle or ignore (see Chapter 10) or when an unrecoverable CPU exception has been raised in Kernel Mode while the kernel was running on behalf of the process (see Chapter 4). 3.5.1 Process Termination All process terminations are handled by the do_exit( ) function, which removes most references to the terminating process from kernel data structures. The do_exit( ) function executes the following actions: 1. Sets the PF_EXITING flag in the flag field of the process descriptor to indicate that the process is being eliminated. 2. Removes, if necessary, the process descriptor from an IPC semaphore queue via the sem_exit( ) function (see Chapter 19) or from a dynamic timer queue via the del_timer_sync( ) function (see Chapter 6). 3. Examines the process's data structures related to paging, filesystem, open file descriptors, and signal handling, respectively, with the _ _exit_mm( ), _ _exit_files( ), _ _exit_fs( ), and exit_sighand( ) functions. These functions also remove each of these data structures if no other process are sharing them. 4. Decrements the resource counters of the modules used by the process. 5. Sets the exit_code field of the process descriptor to the process termination code. This value is either the _exit( ) system call parameter (normal termination), or an error code supplied by the kernel (abnormal termination). 6. Invokes the exit_notify( ) function to update the parenthood relationships of both the parent process and the child processes. All child processes created by the terminating process become children of another process in the same thread group, if any, or of the init process. Moreover, exit_notify( ) sets the state field of the process descriptor to TASK_ZOMBIE. We shall see what happens to zombie processes in the following section. 7. Invokes the schedule( ) function (see Chapter 11) to select a new process to run. Since a process in a TASK_ZOMBIE state is ignored by the scheduler, the process stops executing right after the switch_to macro in schedule( ) is invoked. 3.5.2 Process Removal The Unix operating system allows a process to query the kernel to obtain the PID of its parent process or the execution state of any of its children. A process may, for instance, create a child process to perform a specific task and then invoke a wait( )-like system call to check whether the child has terminated. If the child has terminated, its termination code will tell the parent process if the task has been carried out successfully. To comply with these design choices, Unix kernels are not allowed to discard data included in a process descriptor field right after the process terminates. They are allowed to do so only after the parent process has issued a wait( )-like system call that refers to the terminated process. This is why the TASK_ZOMBIE state has been introduced: although the process is technically dead, its descriptor must be saved until the parent process is notified. What happens if parent processes terminate before their children? In such a case, the system could be flooded with zombie processes that might end up using all the available task entries. As mentioned earlier, this problem is solved by forcing all orphan processes to become children of the init process. In this way, the init process will destroy the zombies while checking for the termination of one of its legitimate children through a wait( )-like system call. The release_task( ) function releases the process descriptor of a zombie process by executing the following steps: 1. Decrements by 1 the number of processes created up to now by the user owner of the terminated process. This value is stored in the user_struct structure mentioned earlier in the chapter. 2. Invokes the free_uid( ) function to decrement by 1 the resource counter of the user_struct structure. 3. Invokes unhash_process( ), which in turn: a. Decrements by 1 the nr_threads variable b. Invokes unhash_pid( ) to remove the process descriptor from the pidhash hash table c. Uses the REMOVE_LINKS macro to unlink the process descriptor from the process list d. Removes the process from its thread group, if any 4. Invokes the free_task_struct( ) function to release the 8-KB memory area used to contain the process descriptor and the Kernel Mode stack. I l@ve RuBoard I l@ve RuBoard Chapter 4. Interrupts and Exceptions An interrupt is usually defined as an event that alters the sequence of instructions executed by a processor. Such events correspond to electrical signals generated by hardware circuits both inside and outside the CPU chip. Interrupts are often divided into synchronous and asynchronous interrupts: ● Synchronous interrupts are produced by the CPU control unit while executing instructions and are called synchronous because the control unit issues them only after terminating the execution of an instruction. ● Asynchronous interrupts are generated by other hardware devices at arbitrary times with respect to the CPU clock signals. Intel microprocessor manuals designate synchronous and asynchronous interrupts as exceptions and interrupts, respectively. We'll adopt this classification, although we'll occasionally use the term "interrupt signal" to designate both types together (synchronous as well as asynchronous). Interrupts are issued by interval timers and I/O devices; for instance, the arrival of a keystroke from a user sets off an interrupt. Exceptions, on the other hand, are caused either by programming errors or by anomalous conditions that must be handled by the kernel. In the first case, the kernel handles the exception by delivering to the current process one of the signals familiar to every Unix programmer. In the second case, the kernel performs all the steps needed to recover from the anomalous condition, such as a Page Fault or a request (via an int instruction) for a kernel service. We start by describing in the next section the motivation for introducing such signals. We then show how the well-known IRQs (Interrupt ReQuests) issued by I/O devices give rise to interrupts, and we detail how 80 x 86 processors handle interrupts and exceptions at the hardware level. Then we illustrate, in Section 4.4, how Linux initializes all the data structures required by the Intel interrupt architecture. The remaining three sections describe how Linux handles interrupt signals at the software level. One word of caution before moving on: in this chapter, we cover only "classic" interrupts common to all PCs; we do not cover the nonstandard interrupts of some architectures. For instance, laptops generate types of interrupts not discussed here. I l@ve RuBoard I l@ve RuBoard 4.1 The Role of Interrupt Signals As the name suggests, interrupt signals provide a way to divert the processor to code outside the normal flow of control. When an interrupt signal arrives, the CPU must stop what it's currently doing and switch to a new activity; it does this by saving the current value of the program counter (i.e., the content of the eip and cs registers) in the Kernel Mode stack and by placing an address related to the interrupt type into the program counter. There are some things in this chapter that will remind you of the context switch described in the previous chapter, carried out when a kernel substitutes one process for another. But there is a key difference between interrupt handling and process switching: the code executed by an interrupt or by an exception handler is not a process. Rather, it is a kernel control path that runs on behalf of the same process that was running when the interrupt occurred (see the later section Section 4.3). As a kernel control path, the interrupt handler is lighter than a process (it has less context and requires less time to set up or tear down). Interrupt handling is one of the most sensitive tasks performed by the kernel, since it must satisfy the following constraints: ● Interrupts can come at any time, when the kernel may want to finish something else it was trying to do. The kernel's goal is therefore to get the interrupt out of the way as soon as possible and defer as much processing as it can. For instance, suppose a block of data has arrived on a network line. When the hardware interrupts the kernel, it could simply mark the presence of data, give the processor back to whatever was running before, and do the rest of the processing later (such as moving the data into a buffer where its recipient process can find it and then restarting the process). The activities that the kernel needs to perform in response to an interrupt are thus divided into two parts: a top half that the kernel executes right away and a bottom half that is left for later. The kernel keeps a queue pointing to all the functions that represent bottom halves waiting to be executed and pulls them off the queue to execute them at particular points in processing. ● Since interrupts can come at any time, the kernel might be handling one of them while another one (of a different type) occurs. This should be allowed as much as possible since it keeps the I/O devices busy (see the later section Section 4.3). As a result, the interrupt handlers must be coded so that the corresponding kernel control paths can be executed in a nested manner. When the last kernel control path terminates, the kernel must be able to resume execution of the interrupted process or switch to another process if the interrupt signal has caused a rescheduling activity. ● Although the kernel may accept a new interrupt signal while handling a previous one, some critical regions exist inside the kernel code where interrupts must be disabled. Such critical regions must be limited as much as possible since, according to the previous requirement, the kernel, and particularly the interrupt handlers, should run most of the time with the interrupts enabled. I l@ve RuBoard I l@ve RuBoard 4.2 Interrupts and Exceptions The Intel documentation classifies interrupts and exceptions as follows: ● Interrupts: Maskable interrupts All Interrupt Requests (IRQs) issued by I/O devices give rise to maskable interrupts. A maskable interrupt can be in two states: masked or unmasked; a masked interrupt is ignored by the control unit as long as it remains masked. Nonmaskable interrupts Only a few critical events (such as hardware failures) give rise to nonmaskable interrupts. Nonmaskable interrupts are always recognized by the CPU. ● Exceptions: Processor-detected exceptions Generated when the CPU detects an anomalous condition while executing an instruction. These are further divided into three groups, depending on the value of the eip register that is saved on the Kernel Mode stack when the CPU control unit raises the exception. Faults Can generally be corrected; once corrected, the program is allowed to restart with no loss of continuity. The saved value of eip is the address of the instruction that caused the fault, and hence that instruction can be resumed when the exception handler terminates. As we shall see in Section 8.4, resuming the same instruction is necessary whenever the handler is able to correct the anomalous condition that caused the exception. Traps Reported immediately following the execution of the trapping instruction; after the kernel returns control to the program, it is allowed to continue its execution with no loss of continuity. The saved value of eip is the address of the instruction that should be executed after the one that caused the trap. A trap is triggered only when there is no need to reexecute the instruction that terminated. The main use of traps is for debugging purposes. The role of the interrupt signal in this case is to notify the debugger that a specific instruction has been executed (for instance, a breakpoint has been reached within a program). Once the user has examined the data provided by the debugger, she may ask that execution of the debugged program resume, starting from the next instruction. Aborts A serious error occurred; the control unit is in trouble, and it may be unable to store in the eip register the precise location of the instruction causing the exception. Aborts are used to report severe errors, such as hardware failures and invalid or inconsistent values in system tables. The interrupt signal sent by the control unit is an emergency signal used to switch control to the corresponding abort exception handler. This handler has no choice but to force the affected process to terminate. Programmed exceptions Occur at the request of the programmer. They are triggered by int or int3 instructions; the into (check for overflow) and bound (check on address bound) instructions also give rise to a programmed exception when the condition they are checking is not true. Programmed exceptions are handled by the control unit as traps; they are often called software interrupts. Such exceptions have two common uses: to implement system calls and to notify a debugger of a specific event (see Chapter 9). Each interrupt or exception is identified by a number ranging from 0 to 255; Intel calls this 8- bit unsigned number a vector. The vectors of nonmaskable interrupts and exceptions are fixed, while those of maskable interrupts can be altered by programming the Interrupt Controller (see the next section). 4.2.1 IRQs and Interrupts Each hardware device controller capable of issuing interrupt requests has an output line designated as an Interrupt ReQuest (IRQ). All existing IRQ lines are connected to the input pins of a hardware circuit called the Interrupt Controller, which performs the following actions: 1. Monitors the IRQ lines, checking for raised signals. 2. If a raised signal occurs on an IRQ line: a. Converts the raised signal received into a corresponding vector. b. Stores the vector in an Interrupt Controller I/O port, thus allowing the CPU to read it via the data bus. c. Sends a raised signal to the processor INTR pin—that is, issues an interrupt. d. Waits until the CPU acknowledges the interrupt signal by writing into one of the Programmable Interrupt Controllers (PIC) I/O ports; when this occurs, clears the INTR line. 3. Goes back to Step 1. The IRQ lines are sequentially numbered starting from 0; therefore, the first IRQ line is usually denoted as IRQ0. Intel's default vector associated with IRQn is n+32. As mentioned before, the mapping between IRQs and vectors can be modified by issuing suitable I/O instructions to the Interrupt Controller ports. Each IRQ line can be selectively disabled. Thus, the PIC can be programmed to disable IRQs. That is, the PIC can be told to stop issuing interrupts that refer to a given IRQ line, or to enable them. Disabled interrupts are not lost; the PIC sends them to the CPU as soon as they are enabled again. This feature is used by most interrupt handlers since it allows them to process IRQs of the same type serially. Selective enabling/disabling of IRQs is not the same as global masking/unmasking of maskable interrupts. When the IF flag of the eflags register is clear, each maskable interrupt issued by the PIC is temporarily ignored by the CPU. The cli and sti assembly language instructions, respectively, clear and set that flag. Masking and unmasking interrupts on a multiprocessor system is trickier since each CPU has its own eflags register. We'll deal with this topic in Chapter 5. Traditional PICs are implemented by connecting "in cascade" two 8259A-style external chips. Each chip can handle up to eight different IRQ input lines. Since the INT output line of the slave PIC is connected to the IRQ2 pin of the master PIC, the number of available IRQ lines is limited to 15. 4.2.1.1 The Advanced Programmable Interrupt Controller (APIC) The previous description refers to PICs designed for uniprocessor systems. If the system includes a single CPU, the output line of the master PIC can be connected in a straightforward way to the INTR pin the CPU. However, if the system includes two or more CPUs, this approach is no longer valid and more sophisticated PICs are needed. Being able to deliver interrupts to each CPU in the system is crucial for fully exploiting the parallelism of the SMP architecture. For that reason, Intel has introduced a new component designated as the I/O Advanced Programmable Interrupt Controller (I/O APIC), which replaces the old 8259A Programmable Interrupt Controller. Moreover, all current Intel CPUs include a local APIC. Each Local APIC has 32-bit registers, an internal clock, a local timer device, and two additional IRQ lines LINT0 and LINT1 reserved for local interrupts. All local APICs are connected to an external I/O APIC, giving raise to a multi-APIC system. Figure 4-1 illustrates in a schematic way the structure of a multi-APIC system. An APIC bus connects the "frontend" I/O APIC to the local APICs. The IRQ lines coming from the devices are connected to the I/O APIC, which therefore acts as a router with respect to the local APICs. In the motherboards of the Pentium III and earlier processors, the APIC bus was a serial three-line bus; starting with the Pentium 4, the APIC bus is implemented by means of the system bus. However, since the APIC bus and its messages are invisible to software, we won't give further details. Figure 4-1. Multi-APIC system The I/O APIC consists of a set of 24 IRQ lines, a 24-entry Interrupt Redirection Table, programmable registers, and a message unit for sending and receiving APIC messages over the APIC bus. Unlike IRQ pins of the 8259A, interrupt priority is not related to pin number: each entry in the Redirection Table can be individually programmed to indicate the interrupt vector and priority, the destination processor, and how the processor is selected. The information in the Redirection Table is used to translate each external IRQ signal into a message to one or more local APIC units via the APIC bus. Interrupt requests coming from external hardware devices can be distributed among the available CPUs in two ways: Static distribution The IRQ signal is delivered to the local APICs listed in the corresponding Redirection Table entry. The interrupt is delivered to one specific CPU, to a subset of CPUs, or to all CPUs at once (broadcast mode). Dynamic distribution The IRQ signal is delivered to the local APIC of the processor that is executing the process with the lowest priority. Any local APIC has a programmable task priority register (TPR), which is used to compute the priority of the currently running process. Intel expects this register to be modified in an operating system kernel by each process switch. If two or more CPUs share the lowest priority, the load is distributed between them using a technique called arbitration. Each CPU is assigned an arbitration priority ranging from 0 to 15 in the arbitration priority register of the local APIC. Every local APIC has a unique value Every time an interrupt is delivered to a CPU, its corresponding arbitration priority is automatically set to 0, while the arbitration priorities of every other CPU is incremented. When the arbitration priority register becomes greater than 15, it is set to the previous arbitration priority of the winning CPU incremented by 1. Therefore, interrupts are distributed in a round-robin fashion among CPUs with the same task priority.[1] [1] The Pentium 4 local APIC doesn't have an arbitration priority register; the arbitration mechanism is hidden in the bus arbitration circuitry. The Intel manuals state that if the operating system kernel does not regularly update the task priority registers, performances may be suboptimal because interrupts might always be serviced by the same CPU. Besides distributing interrupts among processors, the multi-APIC system allows CPUs to generate interprocessor interrupts. When a CPU wishes to send an interrupt to another CPU, it stores the interrupt vector and the identifier of the target's local APIC in the Interrupt Command Register (ICR) of its own local APIC. A message is then sent via the APIC bus to the target's local APIC, which therefore issues a corresponding interrupt to its own CPU. Interprocessor interrupts (in short, IPIs) are part of the SMP architecture and are actively used by Linux to exchange messages among CPUs (see Section 4.6.1.7 later in this chapter). Most of the current uniprocessor systems include an I/O APIC chip, which may be configured in two distinct ways: ● As a standard 8259A-style external PIC connected to the CPU. The local APIC is disabled and the two LINT0 and LINT1 local IRQ lines are configured, respectively, as the INTR and NMI pins. ● As a standard external I/O APIC. The local APIC is enabled and all external interrupts are received through the I/O APIC. 4.2.2 Exceptions The 80 x 86 microprocessors issue roughly 20 different exceptions.[2] The kernel must provide a dedicated exception handler for each exception type. For some exceptions, the CPU control unit also generates a hardware error code and pushes it in the Kernel Mode stack before starting the exception handler. [2] The exact number depends on the processor model. The following list gives the vector, the name, the type, and a brief description of the exceptions found in 80 x 86 processors. Additional information may be found in the Intel technical documentation. 0 - "Divide error" (fault) Raised when a program issues an integer division by 0. 1- "Debug" (trap or fault) Raised when the T flag of eflags is set (quite useful to implement step-by-step execution of a debugged program) or when the address of an instruction or operand falls within the range of an active debug register (see Section 3.3.1). 2 - Not used Reserved for nonmaskable interrupts (those that use the NMI pin). 3 - "Breakpoint" (trap) Caused by an int3 (breakpoint) instruction (usually inserted by a debugger). 4 - "Overflow" (trap) An into (check for overflow) instruction has been executed when the OF (overflow) flag of eflags is set. 5 - "Bounds check" (fault) A bound (check on address bound) instruction is executed with the operand outside of the valid address bounds. 6 - "Invalid opcode" (fault) The CPU execution unit has detected an invalid opcode (the part of the machine instruction that determines the operation performed). 7 - "Device not available" (fault) An ESCAPE, MMX, or XMM instruction has been executed with the TS flag of cr0 set (see Section 3.3.4). 8 - "Double fault" (abort) Normally, when the CPU detects an exception while trying to call the handler for a prior exception, the two exceptions can be handled serially. In a few cases, however, the processor cannot handle them serially, so it raises this exception. 9 - "Coprocessor segment overrun" (abort) Problems with the external mathematical coprocessor (applies only to old 80386 microprocessors). 10 - "Invalid TSS" (fault) The CPU has attempted a context switch to a process having an invalid Task State Segment. 11 - "Segment not present" (fault) A reference was made to a segment not present in memory (one in which the Segment-Present flag of the Segment Descriptor was cleared). 12 - "Stack segment" (fault) The instruction attempted to exceed the stack segment limit, or the segment identified by ss is not present in memory. 13 - "General protection" (fault) One of the protection rules in the protected mode of the 80 x 86 has been violated. 14 - "Page Fault" (fault) The addressed page is not present in memory, the corresponding Page Table entry is null, or a violation of the paging protection mechanism has occurred. 15 - Reserved by Intel 16 - "Floating-point error" (fault) The floating-point unit integrated into the CPU chip has signaled an error condition, such as numeric overflow or division by 0.[3] [3] The 80 x 86 microprocessors also generate this exception when performing a signed division whose result cannot be stored as a signed integer (for instance, a division between -2147483648 and -1). 17 - "Alignment check" (fault) The address of an operand is not correctly aligned (for instance, the address of a long integer is not a multiple of 4). 18 - "Machine check" (abort) A machine-check mechanism has detected a CPU or bus error. 19 - "SIMD floating point" (fault) The SSE or SSE2 unit integrated in the CPU chip has signaled an error condition on a floating-point operation. The values from 20 to 31 are reserved by Intel for future development. As illustrated in Table 4-1, each exception is handled by a specific exception handler (see Section 4.5 later in this chapter), which usually sends a Unix signal to the process that caused the exception. Table 4-1. Signals sent by the exception handlers # Exception Exception handler Signal 0 Divide error divide_error( ) SIGFPE 1 Debug debug( ) SIGTRAP 2 NMI nmi( ) None 3 Breakpoint int3( ) SIGTRAP 4 Overflow overflow( ) SIGSEGV 5 Bounds check bounds( ) SIGSEGV 6 Invalid opcode invalid_op( ) SIGILL 7 Device not available device_not_available( ) SIGSEGV 8 Double fault double_fault( ) SIGSEGV 9 Coprocessor segment overrun coprocessor_segment_overrun( ) SIGFPE 10 Invalid TSS invalid_tss( ) SIGSEGV 11 Segment not present segment_not_present( ) SIGBUS 12 Stack exception stack_segment( ) SIGBUS 13 General protection general_protection( ) SIGSEGV 14 Page Fault page_fault( ) SIGSEGV 15 Intel reserved None None 16 Floating-point error coprocessor_error( ) SIGFPE 17 Alignment check alignment_check( ) SIGBUS 18 Machine check machine_check( ) None 19 SIMD floating point simd_coprocessor_error( ) SIGFPE 4.2.3 Interrupt Descriptor Table A system table called Interrupt Descriptor Table (IDT) associates each interrupt or exception vector with the address of the corresponding interrupt or exception handler. The IDT must be properly initialized before the kernel enables interrupts. The IDT format is similar to that of the GDT and the LDTs examined in Chapter 2. Each entry corresponds to an interrupt or an exception vector and consists of an 8-byte descriptor. Thus, a maximum of 256 x 8 = 2048 bytes are required to store the IDT. The idtr CPU register allows the IDT to be located anywhere in memory: it specifies both the IDT base physical address and its limit (maximum length). It must be initialized before enabling interrupts by using the lidt assembly language instruction. The IDT may include three types of descriptors; Figure 4-2 illustrates the meaning of the 64 bits included in each of them. In particular, the value of the Type field encoded in the bits 40-43 identifies the descriptor type. Figure 4-2. Gate descriptors' format The descriptors are: Task gate Includes the TSS selector of the process that must replace the current one when an interrupt signal occurs. Linux does not use task gates. Interrupt gate Includes the Segment Selector and the offset inside the segment of an interrupt or exception handler. While transferring control to the proper segment, the processor clears the IF flag, thus disabling further maskable interrupts. Trap gate Similar to an interrupt gate, except that while transferring control to the proper segment, the processor does not modify the IF flag. As we shall see in the later section Section 4.4.1, Linux uses interrupt gates to handle interrupts and trap gates to handle exceptions. 4.2.4 Hardware Handling of Interrupts and Exceptions We now describe how the CPU control unit handles interrupts and exceptions. We assume that the kernel has been initialized and thus the CPU is operating in Protected Mode. After executing an instruction, the cs and eip pair of registers contain the logical address of the next instruction to be executed. Before dealing with that instruction, the control unit checks whether an interrupt or an exception occurred while the control unit executed the previous instruction. If one occurred, the control unit does the following: 1. Determines the vector i (0 i 255) associated with the interrupt or the exception. 2. Reads the i th entry of the IDT referred by the idtr register (we assume in the following description that the entry contains an interrupt or a trap gate). 3. Gets the base address of the GDT from the gdtr register and looks in the GDT to read the Segment Descriptor identified by the selector in the IDT entry. This descriptor specifies the base address of the segment that includes the interrupt or exception handler. 4. Makes sure the interrupt was issued by an authorized source. First, it compares the Current Privilege Level (CPL), which is stored in the two least significant bits of the cs register, with the Descriptor Privilege Level (DPL) of the Segment Descriptor included in the GDT. Raises a "General protection" exception if the CPL is lower than the DPL because the interrupt handler cannot have a lower privilege than the program that caused the interrupt. For programmed exceptions, it makes a further security check. It compares the CPL with the DPL of the gate descriptor included in the IDT and raises a "General protection" exception if the DPL is lower than the CPL. This last check makes it possible to prevent access by user applications to specific trap or interrupt gates. 5. Checks whether a change of privilege level is taking place — that is, if CPL is different from the selected Segment Descriptor's DPL. If so, the control unit must start using the stack that is associated with the new privilege level. It does this by performing the following steps: a. Reads the tr register to access the TSS segment of the running process. b. Loads the ss and esp registers with the proper values for the stack segment and stack pointer associated with the new privilege level. These values are found in the TSS (see Section 3.3.2). c. In the new stack, saves the previous values of ss and esp, which define the logical address of the stack associated with the old privilege level. 6. If a fault has occurred, loads cs and eip with the logical address of the instruction that caused the exception so that it can be executed again. 7. Saves the contents of eflags, cs, and eip in the stack. 8. If the exception carries a hardware error code, saves it on the stack. 9. Loads cs and eip, respectively, with the Segment Selector and the Offset fields of the Gate Descriptor stored in the i th entry of the IDT. These values define the logical address of the first instruction of the interrupt or exception handler. The last step performed by the control unit is equivalent to a jump to the interrupt or exception handler. In other words, the instruction processed by the control unit after dealing with the interrupt signal is the first instruction of the selected handler. After the interrupt or exception is processed, the corresponding handler must relinquish control to the interrupted process by issuing the iret instruction, which forces the control unit to: 1. Load the cs, eip, and eflags registers with the values saved on the stack. If a hardware error code has been pushed in the stack on top of the eip contents, it must be popped before executing iret. 2. Check whether the CPL of the handler is equal to the value contained in the two least significant bits of cs (this means the interrupted process was running at the same privilege level as the handler). If so, iret concludes execution; otherwise, go to the next step. 3. Load the ss and esp registers from the stack and return to the stack associated with the old privilege level. 4. Examine the contents of the ds, es, fs, and gs segment registers; if any of them contains a selector that refers to a Segment Descriptor whose DPL value is lower than CPL, clear the corresponding segment register. The control unit does this to forbid User Mode programs that run with a CPL equal to 3 from using segment registers previously used by kernel routines (with a DPL equal to 0). If these registers were not cleared, malicious User Mode programs could exploit them in order to access the kernel address space. I l@ve RuBoard I l@ve RuBoard 4.3 Nested Execution of Exception and Interrupt Handlers When handling an interrupt or an exception, the kernel begins a new kernel control path, or separate sequence of instructions. When a process issues a system call request, for instance, the first instructions of the corresponding kernel control path are those that save the content of the registers in the Kernel Mode stack, while the last instructions are those that restore the content of the registers and put the CPU back into User Mode. Linux design does not allow process switching while the CPU is executing a kernel control path associated with an interrupt. However, such kernel control paths may be arbitrarily nested; an interrupt handler may be interrupted by another interrupt handler, thus giving raise to a nested execution of kernel threads. We emphasize that the current process doesn't change while the kernel is handling a nested set of kernel control paths. Assuming that the kernel is bug free, most exceptions can occur only while the CPU is in User Mode. Indeed, they are either caused by programming errors or triggered by debuggers. However, the Page Fault exception may occur in Kernel Mode. This happens when the process attempts to address a page that belongs to its address space but is not currently in RAM. While handling such an exception, the kernel may suspend the current process and replace it with another one until the requested page is available. The kernel control path that handles the Page fault exception resumes execution as soon as the process gets the processor again. Since the Page Fault exception handler never gives rise to further exceptions, at most two kernel control paths associated with exceptions (the first one caused by a system call invocation, the second one caused by a Page Fault) may be stacked, one on top of the other. In contrast to exceptions, interrupts issued by I/O devices do not refer to data structures specific to the current process, although the kernel control paths that handle them run on behalf of that process. As a matter of fact, it is impossible to predict which process will be running when a given interrupt occurs. An interrupt handler may preempt both other interrupt handlers and exception handlers. Conversely, an exception handler never preempts an interrupt handler. The only exception that can be triggered in Kernel Mode is Page Fault, which we just described. But interrupt handlers never perform operations that can induce Page Faults, and thus, potentially, process switch. Linux interleaves kernel control paths for two major reasons: ● To improve the throughput of programmable interrupt controllers and device controllers. Assume that a device controller issues a signal on an IRQ line: the PIC transforms it into an external interrupt, and then both the PIC and the device controller remain blocked until the PIC receives an acknowledgment from the CPU. Thanks to kernel control path interleaving, the kernel is able to send the acknowledgment even when it is handling a previous interrupt. ● To implement an interrupt model without priority levels. Since each interrupt handler may be deferred by another one, there is no need to establish predefined priorities among hardware devices. This simplifies the kernel code and improves its portability. On multiprocessor systems, several kernel control paths may execute concurrently. Moreover, a kernel control path associated with an exception may start executing on a CPU and, due to a process switch, migrate on another CPU. I l@ve RuBoard I l@ve RuBoard 4.4 Initializing the Interrupt Descriptor Table Now that you understand what the Intel processor does with interrupts and exceptions at the hardware level, we can move on to describe how the Interrupt Descriptor Table is initialized. Remember that before the kernel enables the interrupts, it must load the initial address of the IDT table into the idtr register and initialize all the entries of that table. This activity is done while initializing the system (see Appendix A). The int instruction allows a User Mode process to issue an interrupt signal that has an arbitrary vector ranging from 0 to 255. Therefore, initialization of the IDT must be done carefully, to block illegal interrupts and exceptions simulated by User Mode processes via int instructions. This can be achieved by setting the DPL field of the Interrupt or Trap Gate Descriptor to 0. If the process attempts to issue one of these interrupt signals, the control unit checks the CPL value against the DPL field and issues a "General protection" exception. In a few cases, however, a User Mode process must be able to issue a programmed exception. To allow this, it is sufficient to set the DPL field of the corresponding Interrupt or Trap Gate Descriptors to 3 — that is, as high as possible. Let's now see how Linux implements this strategy. 4.4.1 Interrupt, Trap, and System Gates As mentioned in the earlier section Section 4.2.3, Intel provides three types of interrupt descriptors: Task, Interrupt, and Trap Gate Descriptors. Task Gate Descriptors are irrelevant to Linux, but its Interrupt Descriptor Table contains several Interrupt and Trap Gate Descriptors. Linux classifies them as follows, using a slightly different breakdown and terminology from Intel: Interrupt gate An Intel interrupt gate that cannot be accessed by a User Mode process (the gate's DPL field is equal to 0). All Linux interrupt handlers are activated by means of interrupt gates, and all are restricted to Kernel Mode. System gate An Intel trap gate that can be accessed by a User Mode process (the gate's DPL field is equal to 3). The four Linux exception handlers associated with the vectors 3, 4, 5, and 128 are activated by means of system gates, so the four assembly language instructions int3, into, bound, and int $0x80 can be issued in User Mode. Trap gate An Intel trap gate that cannot be accessed by a User Mode process (the gate's DPL field is equal to 0). Most Linux exception handlers are activated by means of trap gates. The following architecture-dependent functions are used to insert gates in the IDT: set_intr_gate(n,addr) Inserts an interrupt gate in the n th IDT entry. The Segment Selector inside the gate is set to the kernel code's Segment Selector. The Offset field is set to addr, which is the address of the interrupt handler. The DPL field is set to 0. set_system_gate(n,addr) Inserts a trap gate in the n th IDT entry. The Segment Selector inside the gate is set to the kernel code's Segment Selector. The Offset field is set to addr, which is the address of the exception handler. The DPL field is set to 3. set_trap_gate(n,addr) Similar to the previous function, except the DPL field is set to 0. 4.4.2 Preliminary Initialization of the IDT The IDT is initialized and used by the BIOS routines when the computer still operates in Real Mode. Once Linux takes over, however, the IDT is moved to another area of RAM and initialized a second time, since Linux does not use any BIOS routines (see Appendix A). The idt variable points to the IDT, while the IDT itself is stored in the idt_table table, which includes 256 entries.[4] The 6-byte idt_descr variable stores both the size of the IDT and its address and is used only when the kernel initializes the idtr register with the lidt assembly language instruction. [4] Some Pentium models have the notorious "f00f" bug, which allows a User Mode program to freeze the system. When executing on such CPUs, Linux uses a workaround based on storing the IDT in a write-protected page frame. The workaround for the bug is offered as an option when the user compiles the kernel. During kernel initialization, the setup_idt( ) assembly language function starts by filling all 256 entries of idt_table with the same interrupt gate, which refers to the ignore_int( ) interrupt handler: setup_idt: lea ignore_int, %edx movl $(_ _KERNEL_CS << 16), %eax movw %dx, %ax /* selector = 0x0010 = cs */ movw $0x8e00, %dx /* interrupt gate, dpl=0, present */ lea idt_table, %edi mov $256, %ecx rp_sidt: movl %eax, (%edi) movl %edx, 4(%edi) addl $8, %edi dec %ecx jne rp_sidt ret The ignore_int( ) interrupt handler, which is in assembly language, may be viewed as a null handler that executes the following actions: 1. Saves the content of some registers in the stack 2. Invokes the printk( ) function to print an "Unknown interrupt" system message 3. Restores the register contents from the stack 4. Executes an iret instruction to restart the interrupted program The ignore_int( ) handler should never be executed. The occurrence of "Unknown interrupt" messages on the console or in the log files denotes either a hardware problem (an I/O device is issuing unforeseen interrupts) or a kernel problem (an interrupt or exception is not being handled properly). Following this preliminary initialization, the kernel makes a second pass in the IDT to replace some of the null handlers with meaningful trap and interrupt handlers. Once this is done, the IDT includes a specialized interrupt, trap, or system gate for each different exception issued by the control unit and for each IRQ recognized by the interrupt controller. The next two sections illustrate in detail how this is done for exceptions and interrupts. I l@ve RuBoard I l@ve RuBoard 4.5 Exception Handling Most exceptions issued by the CPU are interpreted by Linux as error conditions. When one of them occurs, the kernel sends a signal to the process that caused the exception to notify it of an anomalous condition. If, for instance, a process performs a division by zero, the CPU raises a "Divide error" exception and the corresponding exception handler sends a SIGFPE signal to the current process, which then takes the necessary steps to recover or (if no signal handler is set for that signal) abort. There are a couple of cases, however, where Linux exploits CPU exceptions to manage hardware resources more efficiently. A first case is already described in section Section 3.3.4. The "Device not available" exception is used together with the TS flag of the cr0 register to force the kernel to load the floating point registers of the CPU with new values. A second case refers to the Page Fault exception, which is used to defer allocating new page frames to the process until the last possible moment. The corresponding handler is complex because the exception may, or may not, denote an error condition (see Section 8.4). Exception handlers have a standard structure consisting of three parts: 1. Save the contents of most registers in the Kernel Mode stack (this part is coded in assembly language). 2. Handle the exception by means of a high-level C function. 3. Exit from the handler by means of the ret_from_exception( ) function. To take advantage of exceptions, the IDT must be properly initialized with an exception handler function for each recognized exception. It is the job of the trap_init( ) function to insert the final values—the functions that handle the exceptions—into all IDT entries that refer to nonmaskable interrupts and exceptions. This is accomplished through the set_trap_gate, set_intr_gate, and set_system_gate macros: set_trap_gate(0,÷_error); set_trap_gate(1,&debug); set_intr_gate(2,&nmi); set_system_gate(3,&int3); set_system_gate(4,&overflow); set_system_gate(5,&bounds); set_trap_gate(6,&invalid_op); set_trap_gate(7,&device_not_available); set_trap_gate(8,&double_fault); set_trap_gate(9,&coprocessor_segment_overrun); set_trap_gate(10,&invalid_TSS); set_trap_gate(11,&segment_not_present); set_trap_gate(12,&stack_segment); set_trap_gate(13,&general_protection); set_intr_gate(14,&page_fault); set_trap_gate(16,&coprocessor_error); set_trap_gate(17,&alignment_check); set_trap_gate(18,&machine_check); set_trap_gate(19,&simd_coprocessor_error); set_system_gate(128,&system_call); Now we will look at what a typical exception handler does once it is invoked. 4.5.1 Saving the Registers for the Exception Handler Let's use handler_name to denote the name of a generic exception handler. (The actual names of all the exception handlers appear on the list of macros in the previous section.) Each exception handler starts with the following assembly language instructions: handler_name: pushl $0 /* only for some exceptions */ pushl $do_handler_name jmp error_code If the control unit is not supposed to automatically insert a hardware error code on the stack when the exception occurs, the corresponding assembly language fragment includes a pushl $0 instruction to pad the stack with a null value. Then the address of the high-level C function is pushed on the stack; its name consists of the exception handler name prefixed by do_. The assembly language fragment labeled as error_code is the same for all exception handlers except the one for the "Device not available" exception (see Section 3.3.4). The code performs the following steps: 1. Saves the registers that might be used by the high-level C function on the stack. 2. Issues a cld instruction to clear the direction flag DF of eflags, thus making sure that autoincrements on the edi and esi registers will be used with string instructions.[5] [5] A single assembly language "string instruction," such as rep;movsb, is able to act on a whole block of data (string). 3. Copies the hardware error code saved in the stack at location esp+36 in eax. Stores the value -1 in the same stack location. As we shall see in Section 10.3.4, this value is used to separate 0x80 exceptions from other exceptions. 4. Loads edi with the address of the high-level do_handler_name( ) C function saved in the stack at location esp+32; writes the contents of es in that stack location. 5. Loads the kernel data Segment Selector into the ds and es registers, then sets the ebx register to the address of the current process descriptor (see Section 3.2.2). 6. Stores the parameters to be passed to the high-level C function on the stack, namely, the exception hardware error code and the address of the stack location where the contents of User Mode registers is saved. 7. Invokes the high-level C function whose address is now stored in edi. After the last step is executed, the invoked function finds the following on the top locations of the stack: ● The return address of the instruction to be executed after the C function terminates (see the next section) ● The stack address of the saved User Mode registers ● The hardware error code 4.5.2 Entering and Leaving the Exception Handler As already explained, the names of the C functions that implement exception handlers always consist of the prefix do_ followed by the handler name. Most of these functions store the hardware error code and the exception vector in the process descriptor of current, and then send a suitable signal to that process. This is done as follows: current->tss.error_code = error_code; current->tss.trap_no = vector; force_sig(sig_number, current); The current process takes care of the signal right after the termination of exception handler. The signal will be handled either in User Mode by the process's own signal handler (if it exists) or in Kernel Mode. In the latter case, the kernel usually kills the process (see Chapter 10). The signals sent by the exception handlers are already in Table 4-1. The exception handler always checks whether the exception occurred in User Mode or in Kernel Mode and, in the latter case, whether it was due to an invalid argument of a system call. We'll describe in Section 9.2.6 how the kernel defends itself against invalid arguments of system calls. Any other exception raised in Kernel Mode is due to a kernel bug. In this case, the exception handler knows the kernel is misbehaving and, in order to avoid data corruption on the hard disks, the handler invokes the die( ) function, which prints the contents of all CPU registers on the console (this dump is called kernel oops) and terminates the current process by calling do_exit( ) (see Chapter 20). When the C function that implements the exception handling terminates, control is transferred to the following assembly language fragment: addl $8, %esp jmp ret_from_exception The code pops the stack address of the saved User Mode registers and the hardware error code from the stack, and then performs a jmp instruction to the ret_from_exception( ) function. This function is described in the later section Section 4.8. I l@ve RuBoard I l@ve RuBoard 4.6 Interrupt Handling As we explained earlier, most exceptions are handled simply by sending a Unix signal to the process that caused the exception. The action to be taken is thus deferred until the process receives the signal; as a result, the kernel is able to process the exception quickly. This approach does not hold for interrupts because they frequently arrive long after the process to which they are related (for instance, a process that requested a data transfer) has been suspended and a completely unrelated process is running. So it would make no sense to send a Unix signal to the current process. Interrupt handling depends on the type of interrupt. For our purposes, we'll distinguish three main classes of interrupts: I/O interrupts Some I/O devices require attention; the corresponding interrupt handler must query the device to determine the proper course of action. We cover this type of interrupt in the later section Section 4.6.1. Timer interrupts Some timer, either a local APIC timer or an external timer, has issued an interrupt; this kind of interrupt tells the kernel that a fixed-time interval has elapsed. These interrupts are handled mostly as I/O interrupts; we discuss the peculiar characteristics of timer interrupts in Chapter 6. Interprocessor interrupts A CPU issued an interrupt to another CPU of a multiprocessor system. We cover such interrupts in the later section Section 4.6.2. 4.6.1 I/O Interrupt Handling In general, an I/O interrupt handler must be flexible enough to service several devices at the same time. In the PCI bus architecture, for instance, several devices may share the same IRQ line. This means that the interrupt vector alone does not tell the whole story. In the example shown in Table 4-3, the same vector 43 is assigned to the USB port and to the sound card. However, some hardware devices found in older PC architectures (like ISA) do not reliably operate if their IRQ line is shared with other devices. Interrupt handler flexibility is achieved in two distinct ways, as discussed in the following list. IRQ sharing The interrupt handler executes several interrupt service routines (ISRs). Each ISR is a function related to a single device sharing the IRQ line. Since it is not possible to know in advance which particular device issued the IRQ, each ISR is executed to verify whether its device needs attention; if so, the ISR performs all the operations that need to be executed when the device raises an interrupt. IRQ dynamic allocation An IRQ line is associated with a device at the last possible moment; for instance, the IRQ line of the floppy device is allocated only when a user accesses the floppy disk device. In this way, the same IRQ vector may be used by several hardware devices even if they cannot share the IRQ line, although not at the same time. Not all actions to be performed when an interrupt occurs have the same urgency. In fact, the interrupt handler itself is not a suitable place for all kind of actions. Long noncritical operations should be deferred, since while an interrupt handler is running, the signals on the corresponding IRQ line are temporarily ignored. Most important, the process on behalf of which an interrupt handler is executed must always stay in the TASK_RUNNING state, or a system freeze can occur. Therefore, interrupt handlers cannot perform any blocking procedure such as an I/O disk operation. Linux divides the actions to be performed following an interrupt into three classes: Critical Actions such as acknowledging an interrupt to the PIC, reprogramming the PIC or the device controller, or updating data structures accessed by both the device and the processor. These can be executed quickly and are critical because they must be performed as soon as possible. Critical actions are executed within the interrupt handler immediately, with maskable interrupts disabled. Noncritical Actions such as updating data structures that are accessed only by the processor (for instance, reading the scan code after a keyboard key has been pushed). These actions can also finish quickly, so they are executed by the interrupt handler immediately, with the interrupts enabled. Noncritical deferrable Actions such as copying a buffer's contents into the address space of some process (for instance, sending the keyboard line buffer to the terminal handler process). These may be delayed for a long time interval without affecting the kernel operations; the interested process will just keep waiting for the data. Noncritical deferrable actions are performed by means of separate functions that are discussed in the later section Section 4.7. Regardless of the kind of circuit that caused the interrupt, all I/O interrupt handlers perform the same four basic actions: 1. Save the IRQ value and the registers contents in the Kernel Mode stack. 2. Send an acknowledgment to the PIC that is servicing the IRQ line, thus allowing it to issue further interrupts. 3. Execute the interrupt service routines (ISRs) associated with all the devices that share the IRQ. 4. Terminate by jumping to the ret_from_intr( ) address. Several descriptors are needed to represent both the state of the IRQ lines and the functions to be executed when an interrupt occurs. Figure 4-3 represents in a schematic way the hardware circuits and the software functions used to handle an interrupt. These functions are discussed in the following sections. Figure 4-3. I/O interrupt handling 4.6.1.1 Interrupt vectors As illustrated in Table 4-2, physical IRQs may be assigned any vector in the range 32-238. However, Linux uses vector 128 to implement system calls. The IBM-compatible PC architecture requires that some devices be statically connected to specific IRQ lines. In particular: ● The interval timer device must be connected to the IRQ0 line (see Chapter 6). ● The slave 8259A PIC must be connected to the IRQ2 line (although more advanced PICs are now being used, Linux still supports 8259A-style PICs). ● The external mathematical coprocessor must be connected to the IRQ13 line (although recent 80 x 86 processors no longer use such a device, Linux continues to support the hardy 80386 model). ● In general, an I/O device can be connected to a limited number of IRQ lines. (As a matter of fact, when playing with an old PC where IRQ sharing is not possible, you might not succeed in installing a new card because of IRQ conflicts with other already present hardware devices.) Table 4-2. Interrupt vectors in Linux Vector range Use 0-19 (0x0-0x13) Nonmaskable interrupts and exceptions 20-31 (0x14-0x1f) Intel-reserved 32-127 (0x20-0x7f) External interrupts (IRQs) 128 (0x80) Programmed exception for system calls (see Chapter 9) 129-238 (0x81-0xee) External interrupts (IRQs) 239 (0xef) Local APIC timer interrupt (see Chapter 6) 240-250 (0xf0-0xfa) Reserved by Linux for future use 251-255 (0xfb-0xff) Interprocessor interrupts (see Section 4.6.2 later in this chapter) There are three ways to select a line for an IRQ-configurable device: ● By setting some hardware jumpers (only on very old device cards). ● By a utility program shipped with the device and executed when installing it. Such a program may either ask the user to select an available IRQ number or probe the system to determine an available number by itself. ● By a hardware protocol executed at system startup. Peripheral devices declare which interrupt lines they are ready to use; the final values are then negotiated to reduce conflicts as much as possible. Once this is done, each interrupt handler can read the assigned IRQ by using a function that accesses some I/O ports of the device. For instance, drivers for devices that comply with the Peripheral Component Interconnect (PCI) standard use a group of functions such as pci_read_config_byte( ) to access the device configuration space. Table 4-3 shows a fairly arbitrary arrangement of devices and IRQs, such as those that might be found on one particular PC. Table 4-3. An example of IRQ assignment to I/O devices IRQ INT Hardware Device 0 32 Timer 1 33 Keyboard 2 34 PIC cascading 3 35 Second serial port 4 36 First serial port 6 38 Floppy disk 8 40 System clock 10 42 Network interface 11 43 USB port, sound card 12 44 PS/2 mouse 13 45 Mathematical coprocessor 14 46 EIDE disk controller's first chain 15 47 EIDE disk controller's second chain The kernel must discover the correspondence between the IRQ number and the I/O device before enabling interrupts. Otherwise, how could the kernel handle a signal from, for example, a SCSI disk without knowing which vector corresponds to the device? The correspondence is established while initializing each device driver (see Chapter 13). 4.6.1.2 IRQ data structures As always, when discussing complicated operations involving state transitions, it helps to understand first where key data is stored. Thus, this section explains the data structures that support interrupt handling and how they are laid out in various descriptors. Figure 4-4 illustrates schematically the relationships between the main descriptors that represent the state of the IRQ lines. (The figure does not illustrate the data structures needed to handle softirqs, tasklets, and bottom halves; they are discussed later in this chapter.) Figure 4-4. IRQ descriptors An irq _desc array groups together NR_IRQS (usually 224) irq _desc_t descriptors, which include the following fields: status A set of flags describing the IRQ line status (see Table 4-4). Table 4-4. Flags describing the IRQ line status Flag name Description IRQ_INPROGRESS A handler for the IRQ is being executed. IRQ_DISABLED The IRQ line has been deliberately disabled by a device driver. IRQ_PENDING An IRQ has occurred on the line; its occurrence has been acknowledged to the PIC, but it has not yet been serviced by the kernel. IRQ_REPLAY The IRQ line has been disabled but the previous IRQ occurrence has not yet been acknowledged to the PIC. IRQ_AUTODETECT The kernel uses the IRQ line while performing a hardware device probe. IRQ_WAITING The kernel uses the IRQ line while performing a hardware device probe; moreover, the corresponding interrupt has not been raised. IRQ_LEVEL Not used on the 80 x 86 architecture. IRQ_MASKED Not used. IRQ_PER_CPU Not used on the 80 x 86 architecture. handler Points to the hw_interrupt_type descriptor that identifies the PIC circuit servicing the IRQ line. action Identifies the interrupt service routines to be invoked when the IRQ occurs. The field points to the first element of the list of irqaction descriptors associated with the IRQ. The irqaction descriptor is described later in the chapter. depth Shows 0 if the IRQ line is enabled and a positive value if it has been disabled at least once. Every time the disable_irq( ) or disable_irq_nosync( ) function is invoked, the field is incremented; if depth was equal to 0, the function disables the IRQ line and sets its IRQ_DISABLED flag.[6] Conversely, each invocation of the enable_irq( ) function decrements the field; if depth becomes 0, the function enables the IRQ line and clears its IRQ_DISABLED flag. [6] Contrary to disable_irq_nosync( ), disable_irq(n) waits until all interrupt handlers for IRQn that are running on other CPUs have completed before returning. lock A spin lock used to serialize the accesses to the IRQ descriptor (see Chapter 5). During system initialization, the init_IRQ( ) function sets the status field of each IRQ main descriptor to IRQ _DISABLED. Moreover, init_IRQ( ) updates the IDT by replacing the provisional interrupt gates with new ones. This is accomplished through the following statements: for (i = 0; i < NR_IRQS; i++) if (i+32 != 128) set_intr_gate(i+32,interrupt[i]); This code looks in the interrupt array to find the interrupt handler addresses that it uses to set up the interrupt gates. The interrupt handler for IRQn is named IRQn_interrupt( ) (see the later section Section 4.6.1.4). Some of the interrupt gates will never be used; others will be used only in multiprocessor systems; finally, some of them are always used. Thus, some of the interrupt gates are set to their final values, while others aren't. More precisely: ● The gates of the first 16 IRQs (vectors 32-47) are set to their final values. ● In multiprocessor systems, the gates of the interprocessor interrupts and the gate of the local APIC timer interrupt are also set properly (see Section 4.6.1.7 later in this chapter). ● Vector 128 is left untouched, since it is used for the system call's programmed exception. ● All remaining gates are reserved for interrupts issued from devices connected to a PCI bus. In this case, the handler field of the irq_desc element is initialized to the no_irq_type null handler. In addition to the 8259A chip that was mentioned near the beginning of this chapter, Linux supports several other PIC circuits such as the SMP IO-APIC, PIIX4's internal 8259 PIC, and SGI's Visual Workstation Cobalt (IO-)APIC. To handle all such devices in a uniform way, Linux uses a "PIC object," consisting of the PIC name and seven PIC standard methods. The advantage of this object-oriented approach is that drivers need not to be aware of the kind of PIC installed in the system. Each driver-visible interrupt source is transparently wired to the appropriate controller. The data structure that defines a PIC object is called hw_interrupt_type (also called hw_irq_controller). For the sake of concreteness, let's assume that our computer is a uniprocessor with two 8259A PICs, which provide 16 standard IRQs. In this case, the handler field in each of the 16 irq _desc_t descriptors points to the i8259A_irq _type variable, which describes the 8259A PIC. This variable is initialized as follows: struct hw_interrupt_type i8259A_irq_type = { "XT-PIC", startup_8259A_irq, shutdown_8259A_irq, enable_8259A_irq, disable_8259A_irq, mask_and_ack_8259A, end_8259A_irq, NULL }; The first field in this structure, "XT-PIC", is the PIC name. Next come the pointers to six different functions used to program the PIC. The first two functions start up and shut down an IRQ line of the chip, respectively. But in the case of the 8259A chip, these functions coincide with the third and fourth functions, which enable and disable the line. The mask_and_ack_8259A( ) function acknowledges the IRQ received by sending the proper bytes to the 8259A I/O ports. The end_8259A_irq( ) function is invoked when the interrupt handler for the IRQ line terminates. The last set_affinity method is set to NULL: it is used in multiprocessor systems to declare the "affinity" of CPUs for specified IRQs — that is, which CPUs are enabled to handle specific IRQs. As described earlier, multiple devices can share a single IRQ. Therefore, the kernel maintains irqaction descriptors, each of which refers to a specific hardware device and a specific interrupt. The descriptor includes the following fields: handler Points to the interrupt service routine for an I/O device. This is the key field that allows many devices to share the same IRQ. flags Describes the relationships between the IRQ line and the I/O device (see Table 4-5). Table 4-5. Flags of the irqaction descriptor Flag name Description SA_INTERRUPT The handler must execute with interrupts disabled. SA_SHIRQ The device permits its IRQ line to be shared with other devices. SA_SAMPLE_RANDOM The device may be considered a source of events that occurs randomly; it can thus be used by the kernel random number generator. (Users can access this feature by taking random numbers from the /dev/random and /dev/urandom device files.) name The name of the I/O device (shown when listing the serviced IRQs by reading the /proc/interrupts file). dev_id A private field for the I/O device. Typically, it identifies the I/O device itself (for instance, it could be equal to its major and minor numbers; see Section 13.2), or it points to a device driver's data. next Points to the next element of a list of irqaction descriptors. The elements in the list refer to hardware devices that share the same IRQ. Finally, the irq_stat array includes NR_CPUS entries, one for each CPU in the system. Each entry is of type irq_cpustat_t, and includes a few counters and flags used by the kernel to keep track of what any CPU is currently doing. The most important fields are usually accessed through some macros having as a parameter the CPU logical number (that is, the index of the array). In particular, the local_irq_count(n) macro selects the _ _local_irq_count field of the nth entry of the array. The field is a counter of how many interrupt handlers are stacked in the CPU — that is, how many interrupt handlers have been started and are not yet terminated. 4.6.1.3 IRQ distribution in multiprocessor systems Linux sticks to the Symmetric Multiprocessing model (SMP); this means, essentially, that the kernel should not have any bias toward one CPU with respect to the others. As a consequence, the kernel tries to distribute the IRQ signals coming from the hardware devices in a round-robin fashion among all the CPUs. Therefore, all the CPUs spend approximately the same fraction of their execution time servicing I/O interrupts. In the earlier section Section 4.2.1.1, we said that the multi-APIC system has sophisticated mechanisms to dynamically distribute the IRQ signals among the CPUs. Therefore, the Linux kernel has to do very little to enforce the round-robin distribution scheme. During system bootstrap, the booting CPU executes the setup_IO_APIC_irqs( ) function to initialize the I/O APIC chip. The 24 entries of the Interrupt Redirection Table of the chip are filled so that all IRQ signals from the I/O hardware devices can be routed to each CPU in the system according to the "lowest priority" scheme. During system bootstrap, moreover, all CPUs execute the setup_local_APIC( ) function, which takes care of initializing the local APICs. In particular, the task priority register (TPR) of each chip is initialized to a fixed value, meaning that the CPU is willing to handle any kind of IRQ signal, regardless of its priority. The Linux kernel never modifies this value after its initialization. Since all task priority registers contain the same value, all CPUs always have the same priority. To break tie, the multi-APIC system uses the values in the arbitration priority registers of local APICs, as explained earlier. Since such values are automatically changed after every interrupt, the IRQ signals are fairly distributed among all CPUs.[7] [7] There is an exception, though. Linux usually sets up the local APICs in such a way to honor the focus processor. When an IRQ signal is raised, the focus processor for that IRQ is the CPU to which a previous occurrence of the same IRQ has been already sent; moreover, either the interrupt is still pending (waiting to be handled) or the CPU is still servicing the corresponding interrupt handler. When focus mode is enabled, an interrupt is always sent to its focus processor, if it exists. However, Intel has dropped support for focus processors in the Pentium 4 model. In short, when a hardware device raises an IRQ signal, the multi-APIC system selects one of the CPUs and delivers the signal to the corresponding local APIC, which in turn interrupts its CPU. All other CPUs are not notified of the event. All this is magically done by the hardware, so it is of no concern for the kernel after multi-APIC system initialization. 4.6.1.4 Saving the registers for the interrupt handler When a CPU receives an interrupt, it starts executing the code at the address found in the corresponding gate of the IDT (see the earlier section Section 4.2.4). As with other context switches, the need to save registers leaves the kernel developer with a somewhat messy coding job because the registers have to be saved and restored using assembly language code. However, within those operations, the processor is expected to call and return from a C function. In this section, we describe the assembly language task of handling registers; in the next, we show some of the acrobatics required in the C function that is subsequently invoked. Saving registers is the first task of the interrupt handler. As already mentioned, the interrupt handler for IRQn is named IRQn_interrupt, and its address is included in the interrupt gate stored in the proper IDT entry. In uniprocessor systems, the same BUILD_IRQ macro is duplicated 16 times, once for each IRQ number, in order to yield 16 different interrupt handler entry points. In multiprocessor systems, the macro is duplicated 14 x 16 times for a grand total of 224 interrupt handler entry points. Each macro occurrence expands to the following assembly language fragment: IRQn_interrupt: pushl $n-256 jmp common_interrupt The result is to save on the stack the IRQ number associated with the interrupt minus 256.[8] [8] Subtracting 256 from an IRQ number yields a negative number. Positive numbers are reserved to identify system calls (see Chapter 9). The same code for all interrupt handlers can then be executed while referring to this number. The common code can be found in the BUILD_COMMON_IRQ macro, which expands to the following assembly language fragment: common_interrupt: SAVE_ALL call do_IRQ jmp $ret_from_intr The SAVE_ALL macro, in turn, expands to the following fragment: cld push %es push %ds pushl %eax pushl %ebp pushl %edi pushl %esi pushl %edx pushl %ecx pushl %ebx movl $_ _KERNEL_DS,%edx movl %edx,%ds movl %edx,%es SAVE_ALL saves all the CPU registers that may be used by the interrupt handler on the stack, except for eflags, cs, eip, ss, and esp, which are already saved automatically by the control unit (see the earlier section Section 4.2.4). The macro then loads the selector of the kernel data segment into ds and es. After saving the registers, BUILD_COMMON_IRQ invokes the do_IRQ( ) function. Then, when the ret instruction of do_IRQ( ) is executed (when that function terminates) control is transferred to ret_from_intr( ) (see the later section Section 4.8). 4.6.1.5 The do_IRQ( ) function The do_IRQ( ) function is invoked to execute all interrupt service routines associated with an interrupt. When it starts, the kernel stack contains, from the top down: ● The do_IRQ( )'s return address (the starting address of ret_from_intr( )) ● The group of register values pushed on by SAVE_ALL ● The encoding of the IRQ number ● The registers saved automatically by the control unit when it recognized the interrupt Since the C compiler places all the parameters on top of the stack, the do_IRQ( ) function is declared as follows: unsigned int do_IRQ(struct pt_regs regs) where the pt_regs structure consists of 15 fields: ● The first nine fields are the register values pushed by SAVE_ALL. ● The tenth field, referenced through a field called orig_eax, encodes the IRQ number. ● The remaining fields correspond to the register values pushed on automatically by the control unit.[9] [9] The ret_from_intr( ) return address is missing from the pt_regs structure because the C compiler expects a return address on top of the stack. It takes this into account when generating the instructions to address parameters. The do_IRQ( ) function is equivalent to the following code fragment. Don't be scared by this function — we are going to explain the code line by line. int irq = regs.orig_eax & 0xff; spin_lock(&(irq_desc[irq].lock)); irq_desc[irq].handler->ack(irq); irq_desc[irq].status &= ~(IRQ_REPLAY | IRQ_WAITING); irq_desc[irq].status |= IRQ_PENDING; if (!(irq_desc[irq].status & (IRQ_DISABLED | IRQ_INPROGRESS)) && irq_desc[irq].action) { irq_desc[irq].status |= IRQ_INPROGRESS; do { irq_desc[irq].status &= ~IRQ_PENDING; spin_unlock(&(irq_desc[irq].lock)); handle_IRQ_event(irq, ®s, irq_desc[irq].action); spin_lock(&(irq_desc[irq].lock)); } while (irq_desc[irq].status & IRQ_PENDING); irq_desc[irq].status &= ~IRQ_INPROGRESS; } irq_desc[irq].handler->end(irq); spin_unlock(&(irq_desc[irq].lock)); if (softirq_pending(smp_processor_id( ))) do_softirq( ); First of all, the do_IRQ( ) function gets the IRQ vector passed as a parameter on the stack and puts it in the irq local variable. This value is used as an index to access the proper element of the irq_desc array (the IRQ main descriptor). Before accessing the main IRQ descriptor, the kernel acquires the corresponding spin lock. We'll see in Chapter 5 that the spin lock protects against concurrent accesses by different CPUs (in a uniprocessor system, the spin_lock( ) function does nothing). This spin lock is necessary in a multiprocessor system because other interrupts of the same kind may be raised, and other CPUs might take care of the new interrupt occurrences. Without the spin lock, the main IRQ descriptor would be accessed concurrently by several CPUs. As we'll see, this situation must be absolutely avoided. After acquiring the spin lock, the function invokes the ack method of the main IRQ descriptor. In a uniprocessor system, the corresponding mask_and_ack_8259A( ) function acknowledges the interrupt on the PIC and also disables the IRQ line. Masking the IRQ line ensures that the CPU does not accept further occurrences of this type of interrupt until the handler terminates. Remember that the do_IRQ( ) function runs with local interrupts disabled; in fact, the CPU control unit automatically clears the IF flag of the eflags register because the interrupt handler is invoked through an IDT's interrupt gate. However, we'll see shortly that the kernel might re-enable local interrupts before executing the interrupt service routines of this interrupt. In a multiprocessor system, however, things are much more complicated. Depending on the type of interrupt, acknowledging the interrupt could either be done by the ack method or delayed until the interrupt handler terminates (that is, acknowledgement could be done by the end method). In either case, we can take for granted that the local APIC doesn't accept further interrupts of this type until the handler terminates, although further occurrences of this type of interrupt may be accepted by other CPUs (main IRQ descriptor's spin lock comes to the rescue!). The do_IRQ( ) function then initializes a few flags of the main IRQ descriptor. It sets the IRQ_PENDING flag because the interrupt has been acknowledged (well, sort of), but not yet really serviced; it also clears the IRQ_WAITING and IRQ_REPLAY flags (but we don't have to care about them now). Now do_IRQ( ) checks whether it must really handle the interrupt. There are three cases in which nothing has to be done. These are discussed in the following list. IRQ_DISABLED is set A CPU might execute the do_IRQ( ) function even if the corresponding IRQ line is disabled; you'll find an explanation for this nonintuitive case in the later section Section 4.6.1.6. Moreover, buggy motherboards may generate spurious interrupts even when the IRQ line is disabled in the PIC. IRQ_INPROGRESS is set In a multiprocessor system, another CPU might be handling a previous occurrence of the same interrupt. Why not defer the handling of this occurrence to that CPU? This is exactly what is done by Linux. This leads to a simpler kernel architecture because device drivers' interrupt service routines need not to be reentrant (their execution is serialized). Moreover, the freed CPU can quickly return to what it was doing, without dirtying its hardware cache; this is beneficial to system performances. The IRQ_INPROGRESS flag is set whenever a CPU is committed to execute the interrupt service routines of the interrupt; therefore, the do_IRQ( ) function checks it before starting the real work. irc_desc[irq].action is NULL This case occurs when there is no interrupt service routines associated with the interrupt. Normally, this happens only when the kernel is probing a hardware device. Let's suppose that none of the three cases holds, so the interrupt has to be serviced. do_IRQ( ) sets the IRQ_INPROGRESS flag and starts a loop. In each iteration, the function clears the IRQ_PENDING flag, releases the interrupt spin lock, and executes the interrupt services routines by invoking handle_IRQ_event( )(described in the later section Section 4.6.1.7). When the latter function terminates, do_IRQ( ) acquires the spin lock again and checks the value of the IRQ_PENDING flag. If it is clear, no further occurrence of the interrupt has been delivered to another CPU, so the loop ends. Conversely, if IRQ_PENDING is set, another CPU has executed the do_IRQ( ) function for this type of interrupt while this CPU was executing handle_IRQ_event( ). Therefore, do_IRQ( ) performs another iteration of the loop, servicing the new occurrence of the interrupt.[10] [10] Because IRQ_PENDING is a flag and not a counter, only the second occurrence of the interrupt can be recognized. Further occurrences in each iteration of the do_IRQ( )'s loop are simply lost. Our do_IRQ( ) function is now going to terminate, either because it has already executed the interrupt service routines or because it had nothing to do. The function invokes the end method of the main IRQ descriptor. On uniprocessor systems, the corresponding end_8259A_irq( ) function re-enables the IRQ line (unless the interrupt occurrence was spurious). On multiprocessor systems, the end method acknowledges the interrupt (if not already done by the ack method). Finally, do_IRQ( ) releases the spin lock: the hard work is finished! Before returning, however, the function checks whether deferrable kernel functions are waiting to be executed (see Section 4.7 later in this chapter). In the affirmative case, it invokes the do_softirq( ) function. When do_IRQ( ) terminates, the control is transferred to the ret_from_intr( ) function. 4.6.1.6 Reviving a lost interrupt The do_IRQ( ) function is small and simple, yet it works properly in most cases. Indeed, the IRQ_PENDING, IRQ_INPROGRESS, and IRQ_DISABLED flags ensure that interrupts are correctly handled even when the hardware is misbehaving. However, things may not work so smoothly in a multiprocessor system. Suppose that a CPU has an IRQ line enabled. A hardware device raises the IRQ line, and the multi-APIC system selects our CPU for handling the interrupt. Before the CPU acknowledges the interrupt, the IRQ line is masked out by another CPU; as a consequence, the IRQ_DISABLED flag is set. Right afterwards, our CPU starts handling the pending interrupt; therefore, the do_IRQ( ) function acknowledges the interrupt and then returns without executing the interrupt service routines because it finds the IRQ_DISABLED flag set. Therefore, the interrupt occurred before IRQ line disabling, yet it got lost. To cope with this scenario, when the enable_irq( ) function re-enables the IRQ line, it forces the hardware to generate a new occurrence of the lost interrupt: spin_lock_irqsave(&(irq_desc[irq].lock), flags); if (--irq_desc[irq].depth == 0) { irq_desc[irq].status &= ~IRQ_DISABLED; if (irq_desc[irq].status & (IRQ_PENDING | IRQ_REPLAY)) == IRQ_PENDING) { irq_desc[irq].status |= IRQ_REPLAY; send_IPI_self(irq+32); } irq_desc[irq].handler->enable(irq); } spin_lock_irqrestore(&(irq_desc[irq].lock), flags); The function detects that an interrupt was lost by checking the value of the IRQ_PENDING flag. The flag is always cleared when leaving the interrupt handler; therefore, if the IRQ line is disabled and the flag is set, then an interrupt occurrence has been acknowledged but not yet serviced. In this case it is necessary to issue a new interrupt. This is obtained by forcing the local APIC to generate a self-interrupt (see the later section Section 4.6.2). The role of the IRQ_REPLAY flag is to ensure that exactly one self-interrupt is generated. Remember that the do_IRQ( ) function clears that flag when it starts handling the interrupt. 4.6.1.7 Interrupt service routines As mentioned previously, an interrupt service routine implements a device-specific operation. When an interrupt handler must execute the ISRs, it invokes the handle_IRQ_event( ) function. This function essentially performs the steps shown in the following list. 1. Invokes the irq_enter( ) function to increment the _ _local_irq_count field of the irq_stat entry of the executing CPU (to learn how many interrupt handlers are stacked in the CPU, see the earlier section Section 4.6.1.2). As we shall see in Chapter 5, this function also checks that interrupts are not globally disabled. 2. Enables the local interrupts with the sti assembly language instruction if the SA_INTERRUPT flag is clear. 3. Executes each interrupt service routine of the interrupt through the following code: do { action->handler(irq, action->dev_id, regs); action = action->next; } while (action); At the start of the loop, action points to the start of a list of irqaction data structures that indicate the actions to be taken upon receiving the interrupt (see Figure 4-4 earlier in this chapter). 4. Disables the local interrupts with the cli assembly language instruction. 5. Invokes irq_exit( ) to decrement the _ _local_irq_count field of the irq_stat entry of the executing CPU. All interrupt service routines act on the same parameters: irq The IRQ number dev_id The device identifier regs A pointer to the Kernel Mode stack area containing the registers saved right after the interrupt occurred The first parameter allows a single ISR to handle several IRQ lines, the second one allows a single ISR to take care of several devices of the same type, and the last one allows the ISR to access the execution context of the interrupted kernel control path. In practice, most ISRs do not use these parameters. The SA_INTERRUPT flag of the main IRQ descriptor determines whether interrupts must be enabled or disabled when the do_IRQ( ) function invokes an ISR. An ISR that has been invoked with the interrupts in one state is allowed to put them in the opposite state. In a uniprocessor system, this can be achieved by means of the cli (disable interrupts) and sti (enable interrupts) assembly language instructions. Globally enabling or disabling interrupts in a multiprocessor system is a much more complicated task; we'll deal with it in Chapter 5. The structure of an ISR depends on the characteristics of the device handled. We'll give a few examples of ISRs in Chapter 6, Chapter 13, and Chapter 18. 4.6.1.8 Dynamic allocation of IRQ lines As noticed in section Section 4.6.1.1, a few vectors are reserved for specific devices, while the remaining ones are dynamically handled. There is, therefore, a way in which the same IRQ line can be used by several hardware devices even if they do not allow IRQ sharing. The trick is to serialize the activation of the hardware devices so that just one owns the IRQ line at a time. Before activating a device that is going to use an IRQ line, the corresponding driver invokes request_irq( ). This function creates a new irqaction descriptor and initializes it with the parameter values; it then invokes the setup_irq( ) function to insert the descriptor in the proper IRQ list. The device driver aborts the operation if setup_irq( ) returns an error code, which means that the IRQ line is already in use by another device that does not allow interrupt sharing. When the device operation is concluded, the driver invokes the free_irq( ) function to remove the descriptor from the IRQ list and release the memory area. Let's see how this scheme works on a simple example. Assume a program wants to address the /dev/fd0 device file, which corresponds to the first floppy disk on the system.[11] [11] Floppy disks are "old" devices that do not usually allow IRQ sharing. The program can do this either by directly accessing /dev/fd0 or by mounting a filesystem on it. Floppy disk controllers are usually assigned IRQ 6; given this, the floppy driver issues the following request: request_irq(6, floppy_interrupt, SA_INTERRUPT|SA_SAMPLE_RANDOM, "floppy", NULL); As can be observed, the floppy_interrupt( ) interrupt service routine must execute with the interrupts disabled (SA_INTERRUPT set) and no sharing of the IRQ (SA_SHIRQ flag cleared). The SA_SAMPLE_RANDOM flag set means that accesses to the floppy disk are a good source of random events to be used for the kernel random number generator. When the operation on the floppy disk is concluded (either the I/O operation on /dev/fd0 terminates or the filesystem is unmounted), the driver releases IRQ 6: free_irq(6, NULL); To insert an irqaction descriptor in the proper list, the kernel invokes the setup_irq( ) function, passing to it the parameters irq _nr, the IRQ number, and new (the address of a previously allocated irqaction descriptor). This function: 1. Checks whether another device is already using the irq _nr IRQ and, if so, whether the SA_SHIRQ flags in the irqaction descriptors of both devices specify that the IRQ line can be shared. Returns an error code if the IRQ line cannot be used. 2. Adds *new (the new irqaction descriptor pointed to by new) at the end of the list to which irq _desc[irq _nr]->action points. 3. If no other device is sharing the same IRQ, clears the IRQ _DISABLED, IRQ_AUTODETECT, and IRQ _INPROGRESS flags in the flags field of *new and invokes the startup method of the irq_desc[irq_nr]->handler PIC object to make sure that IRQ signals are enabled. Here is an example of how setup_irq( ) is used, drawn from system initialization. The kernel initializes the irq0 descriptor of the interval timer device by executing the following instructions in the time_init( ) function (see Chapter 6): struct irqaction irq0 = {timer_interrupt, SA_INTERRUPT, 0, "timer", NULL,}; setup_irq(0, &irq0); First, the irq0 variable of type irqaction is initialized: the handler field is set to the address of the timer_interrupt( ) function, the flags field is set to SA_INTERRUPT, the name field is set to "timer", and the last field is set to NULL to show that no dev_id value is used. Next, the kernel invokes setup_irq( ) to insert irq0 in the list of irqaction descriptors associated with IRQ0. 4.6.2 Interprocessor Interrupt Handling On multiprocessor systems, Linux defines the following five kinds of interprocessor interrupts (see also Table 4- 2): CALL_FUNCTION_VECTOR (vector 0xfb) Sent to all CPUs but the sender, forcing those CPUs to run a function passed by the sender. The corresponding interrupt handler is named call_function_interrupt( ). The function passed as a parameter may, for instance, force all other CPUs to stop, or may force them to set the contents of the Memory Type Range Registers (MTRRs).[12] Usually this interrupt is sent to all CPUs except the CPU executing the calling function by means of the smp_call_function( ) facility function. [12] Starting with the Pentium Pro model, Intel microprocessors include these additional registers to easily customize cache operations. For instance, Linux may use these registers to disable the hardware cache for the addresses mapping the frame buffer of a PCI/AGP graphic card while maintaining the "write combining" mode of operation: the paging unit combines write transfers into larger chunks before copying them into the frame buffer. RESCHEDULE_VECTOR (vector 0xfc) When a CPU receives this type of interrupt, the corresponding handler — named reschedule_interrupt( ) — limits itself to acknowledge the interrupt. All the rescheduling is done automatically when returning from the interrupt (see Section 4.8 later in this chapter). INVALIDATE_TLB_VECTOR (vector 0xfd) Sent to all CPUs but the sender, forcing them to invalidate their Translation Lookaside Buffers. The corresponding handler, named invalidate_interrupt( ), flushes some TLB entries of the processor as described in Section 2.5.7. ERROR_APIC_VECTOR (vector 0xfe) This interrupt should never occur. SPURIOUS_APIC_VECTOR (vector 0xff) This interrupt should never occur. Thanks to the following group of functions, issuing interprocessor interrupts (IPIs) becomes an easy task: send_IPI_all( ) Sends an IPI to all CPUs (including the sender) send_IPI_allbutself( ) Sends an IPI to all CPUs except the sender send_IPI_self( ) Sends an IPI to the sender CPU send_IPI_mask( ) Sends an IPI to a group of CPUs specified by a bit mask The assembly language code of the interprocessor interrupt handlers is generated by the BUILD_SMP_INTERRUPT macro; the code is almost identical to the code generated by the BUILD_IRQ macro (see the earlier section Section 4.6.1.4). Each interprocessor interrupt has a different high-level handler, which has the same name as the low-level handler preceded by smp_. For instance, the high-level handler of the RESCHEDULE_VECTOR interprocessor interrupt that is invoked by the low-level reschedule_interrupt( ) handler is named smp_reschedule_interrupt( ). Each high-level handler acknowledges the interprocessor interrupt on the local APIC and then performs the specific action triggered by the interrupt. I l@ve RuBoard I l@ve RuBoard 4.7 Softirqs, Tasklets, and Bottom Halves We mentioned earlier in Section 4.6 that several tasks among those executed by the kernel are not critical: they can be deferred for a long period of time, if necessary. Remember that the interrupt service routines of an interrupt handler are serialized, and often there should be no occurrence of an interrupt until the corresponding interrupt handler has terminated. Conversely, the deferrable tasks can execute with all interrupts enabled. Taking them out of the interrupt handler helps keep kernel response time small. This is a very important property for many time-critical applications that expect their interrupt requests to be serviced in a few milliseconds. Linux 2.4 answers such a challenge by using three kinds of deferrable and interruptible kernel functions (in short, deferrable functions[13]): softirqs, tasklets, and bottom halves. Although these three kinds of deferrable functions work in different ways, they are strictly correlated. Tasklets are implemented on top of softirqs, and bottom halves are implemented by means of tasklets. As a matter of fact, the term "softirq," which appears in the kernel source code, often denotes all kinds of deferrable functions. [13] These are also called software interrupts, but we denote them as "deferrable functions" to avoid confusion with programmed exceptions, which are referred to as "software interrupts" in Intel manuals. As a general rule, no softirq can be interrupted to run another softirq on the same CPU; the same rule holds for tasklets and bottom halves built on top of softirqs. On a multiprocessor system, however, several deferrable functions can run concurrently on different CPUs. The degree of concurrency depends on the type of deferrable function, as shown in Table 4-6. Table 4-6. Differences between softirqs, tasklets, and bottom halves Deferrable function Dynamicallocation Concurrency Softirq No Softirqs of the same type can run concurrently on several CPUs. Tasklet Yes Tasklets of different types can run concurrently on several CPUs, but tasklets of the same type cannot. Bottom half No Bottom halves cannot run concurrently on several CPUs. Softirqs and bottom halves are statically allocated (i.e., defined at compile time), while tasklets can also be allocated and initialized at runtime (for instance, when loading a kernel module). Many softirqs can always be executed concurrently on several CPUs, even if they are of the same type. Generally speaking, softirqs are re-entrant functions and must explicitly protect their data structures with spin locks. Tasklets differ from softirqs because a tasklet is always serialized with respect to itself; in other words, a tasklet cannot be executed by two CPUs at the same time. However, different tasklets can be executed concurrently on several CPUs. Serializing the tasklet simplifies the life of device driver developers, since the tasklet function needs not to be re-entrant. Finally, bottom halves are globally serialized. When one bottom half is in execution on some CPU, the other CPUs cannot execute any bottom half, even if it is of different type. This is a quite strong limitation, since it degrades the performances of the Linux kernel on multiprocessor systems. As a matter of fact, bottom halves continue to be supported by the kernel for compatibility reasons only, and device driver developers are expected to update their old drivers and replace bottom halves with tasklets. Therefore, it is likely that bottom halves will disappear in a future version of Linux. In any case, deferrable functions must be executed serially. Any deferrable function cannot be interleaved with other deferrable functions on the same CPU. Generally speaking, four kinds of operations can be performed on deferrable functions: Initialization Defines a new deferrable function; this operation is usually done when the kernel initializes itself. Activation Marks a deferrable function as "pending" — to be run in the next round of executions of the deferrable functions. Activation can be done at any time (even while handling interrupts). Masking Selectively disables a deferrable function in such a way that it will not be executed by the kernel even if activated. We'll see in Section 5.3.11 that disabling deferrable functions is sometimes essential. Execution Executes a pending deferrable function together with all other pending deferrable functions of the same type; execution is performed at well-specified times, explained later in Section 4.7.1. Activation and execution are somehow bound together: a deferrable function that has been activated by a given CPU must be executed on the same CPU. There is no self-evident reason suggesting that this rule is beneficial for system performances. Binding the deferrable function to the activating CPU could in theory make better use of the CPU hardware cache. After all, it is conceivable that the activating kernel thread accesses some data structures that will also be used by the deferrable function. However, the relevant lines could easily be no longer in the cache when the deferrable function is run because its execution can be delayed a long time. Moreover, binding a function to a CPU is always a potentially "dangerous" operation, since a CPU might end up very busy while the others are mostly idle. 4.7.1 Softirqs Linux 2.4 uses a limited number of softirqs. For most purposes, tasklets are good enough and are much easier to write because they do not need to be re-entrant. As a matter of fact, only the four kinds of softirqs listed in Table 4-7 are currently defined. Table 4-7. Softirqs used in Linux 2.4 Softirq Index (priority) Description HI_SOFTIRQ 0 Handles high-priority tasklets and bottom halves NET_TX_SOFTIRQ 1 Transmits packets to network cards NET_RX_SOFTIRQ 2 Receives packets from network cards TASKLET_SOFTIRQ 3 Handles tasklets The index of a sofirq determines its priority: a lower index means higher priority because softirq functions will be executed starting from index 0. The main data structure used to represent softirqs is the softirq_vec array, which includes 32 elements of type softirq_action. The priority of a softirq is the index of the corresponding softirq_action element inside the array. As shown in Table 4-7, only the first four entries of the array are effectively used. The softirq_action data structure consists of two fields: a pointer to the softirq function and a pointer to a generic data structure that may be needed by the softirq function. The irq_stat array, already introduced in Section 4.6.1.2, includes several fields used by the kernel to implements softirqs (and also tasklets and bottom halves, which depend on softirqs). Each element of the array, corresponding to a given CPU, includes: ● A _ _softirq_pending field that points to a softirq_action structure (the pending softirq). This field may easily be accessed through the softirq_pending macro. ● A _ _local_bh_count field that disables the execution of the softirqs (as well as tasklets and bottom halves). This field may easily be accessed through the local_bh_count macro. If it is set to zero, the softirqs are enabled; alternatively, if the field stores a positive integer, the softirqs are disabled. The local_bh_disable macro increments the field, while the local_bh_enable macro decrements it. If the kernel invokes local_bh_disable twice, it must also call local_bh_enable twice to re-enable softirqs.[14] [14] Better names for these two macros could be local_softirq_disable and local_softirq_enable. The actual names are vestiges of old kernel versions. ● A _ _ksoftirqd_task field that stores the process descriptor address of a ksoftirqd_CPUn kernel thread, which is devoted to the execution of deferrable functions. (There is one such thread per CPU, and the n in ksoftiqd_CPUn represents the CPU index, as described later in Section 4.7.1.1.) This field can be accessed through the ksoftirqd_task macro. The open_softirq( ) function takes care of softirq initialization. It uses three parameters: the softirq index, a pointer to the softirq function to be executed, and a second pointer to a data structure that may be required by the softirq function. open_softirq( ) limits itself to initialize the proper entry of the softirq_vec array. Softirqs are activated by invoking by the _ _cpu_raise_softirq macro, which receives as parameters the CPU number cpu and the softirq index nr, and sets the nrth bit of softirq_pending(cpu). The cpu_raise_softirq( ) function is similar to the _ _cpu_raise_softirq macro, except that it might also wake up the ksoftirqd_CPUn kernel thread. Checks for pending softirqs are performed in a few points of the kernel code. Currently, this is done in the following cases (be warned that number and position of the softirq check points change both with the kernel version and with the supported hardware architecture): ● When the local_bh_enable macro re-enables the softirqs ● When the do_IRQ( ) function finishes handling an I/O interrupt ● When the smp_apic_timer_interrupt( ) function finishes handling a local timer interrupt (see Section 6.2.2) ● When one of the special ksoftirqd_CPUn kernel threads is awoken ● When a packet is received on a network interface card (see Chapter 18) In each check point, the kernel reads softirq_pending(cpu); if this field is not null, the kernel invokes do_softirq( ) to execute the softirq functions. It performs the following actions: 1. Gets the logical number cpu of the CPU that executes the function. 2. Returns if local_irq_count(cpu) is not set to zero. In this case, do_softirq( ) is invoked while terminating a nested interrupt handler, and we know that deferrable functions must run outside of interrupt service routines. 3. Returns if local_bh_count(cpu) is not set to zero. In this case, all deferrable functions are disabled. 4. Saves the state of the IF flag and clears it to disable local interrupts. 5. Checks the softirq_pending(cpu) field of irq_stat. If no softirqs are pending, restores the value of the IF flag saved in the previous step, and then returns. 6. Invokes local_bh_disable(cpu ) to increment the local_bh_count(cpu) field of irq_stat. In this way, deferrable functions are effectively serialized on the CPU because any further invocation of do_softirq( ) returns without executing the softirq functions (see check at Step 3). 7. Executes the following loop: pending = softirq_pending(cpu); softirq_pending(cpu) = 0; mask = 0; do { mask &= ~pending; asm("sti"); for (i=0; pending; pending >>= 1, i++) if (pending & 1) softirq_vec[i].action(softirq_vec+i); asm("cli"); pending = softirq_pending(cpu); } while (pending & mask); As you may see, the function stores the pending softirqs in the pending local variable, and then resets the softirq_pending(cpu) field to zero. In each iteration of the loop, the function: a. Updates the mask local variable; it stores the indices of the softirqs that are already executed in this invocation of the do_softirq( ) function. b. Enables local interrupts. c. Executes the softirq functions of all pending softirqs (inner loop). d. Disables local interrupts. e. Reloads the pending local variable with the contents of the softirq_pending(cpu) field. An interrupt handler, or even a softirq function, could have invoked cpu_raise_softirq( ) while softirq functions were executing. f. Performs another iteration of the loop if a softirq that has not been handled in this invocation of do_softirq( ) is activated. 8. Decrements the local_bh_count(cpu) field, thus re-enabling the softirqs. 9. Checks the value of the pending local variable. If it is not zero, a softirq that was handled in this invocation of do_softirq( ) is activated again. To trigger another execution of the do_softirq( ) function, the function wakes up the ksoftirqd_CPUn kernel thread. 10. Restores the status of IF flag (local interrupts enabled or disabled) saved in Step 4 and returns. 4.7.1.1 The softirq kernel threads In recent kernel versions, each CPU has its own ksoftirqd_CPUn kernel thread (where n is the logical number of the CPU). Each ksoftirqd_CPUn kernel thread runs the ksoftirqd( ) function, which essentially executes the following loop: for(;;) { set_current_state(TASK_INTERRUPTIBLE); schedule( ); /* now in TASK_RUNNING state */ while (softirq_pending(cpu)) { do_softirq( ); if (current->need_resched) schedule( ); } } When awoken, the kernel thread checks the softirq_pending(n) field and invokes, if necessary, do_softirq( ). The ksoftirqd_CPUn kernel threads represent a solution for a critical trade-off problem. Softirq functions may re-activate themselves; actually, both the networking softirqs and the tasklet softirqs do this. Moreover, external events, like packet flooding on a network card, may activate softirqs at very high frequency. The potential for a continuous high-volume flow of softirqs creates a problem that is solved by introducing kernel threads. Without them, developers are essentially faced with two alternative strategies. The first strategy consists of ignoring new softirqs that occur while do_softirq( ) is running. In other words, the do_softirq( ) function determines what softirqs are pending when the function is started, and then executes their functions. Next, it terminates without rechecking the pending softirqs. This solution is not good enough. Suppose that a softirq function is re-activated during the execution of do_softirq( ). In the worst case, the softirq is not executed again until the next timer interrupt, even if the machine is idle. As a result, softirq latency time is unacceptable for networking developers. The second strategy consists of continuously rechecking for pending softirqs. The do_softirq( ) function keeps checking the pending softirqs and terminates only when none of them is pending. While this solution might satisfy networking developers, it can certainly upset normal users of the system: if a high-frequency flow of packets is received by a network card or a softirq function keeps activating itself, the do_softirq( ) function never returns and the User Mode programs are virtually stopped. The ksoftirqd_CPUn kernel threads try to solve this difficult trade-off problem. The do_softirq( ) function determines what softirqs are pending and executes their functions. If an already executed softirq is activated again, the function wakes up the kernel thread and terminates (Step 9 in of do_softirq( )). The kernel thread has low priority, so user programs have a chance to run; but if the machine is idle, the pending softirqs are executed quickly. 4.7.2 Tasklets Tasklets are the preferred way to implement deferrable functions in I/O drivers. As already explained, tasklets are built on top of two softirqs named HI_SOFTIRQ and TASKLET_SOFTIRQ. Several tasklets may be associated with the same softirq, each tasklet carrying its own function. There is no real difference between the two softirqs, except that do_softirq( ) executes HI_SOFTIRQ's tasklets before TASKLET_SOFTIRQ's tasklets. Tasklets and high-priority tasklets are stored in the tasklet_vec and tasklet_hi_vec arrays, respectively. Both of them include NR_CPUS elements of type tasklet_head, and each element consists of a pointer to a list of tasklet descriptors. The tasklet descriptor is a data structure of type tasklet_struct, whose fields are shown in Table 4-8. Table 4-8. The fields of the tasklet descriptor Field name Description next Pointer to next descriptor in the list state Status of the tasklet count Lock counter func Pointer to the tasklet function data An unsigned long integer that may be used by the tasklet function The state field of the tasklet descriptor includes two flags: TASKLET_STATE_SCHED When set, this indicates that the tasklet is pending (has been scheduled for execution); it also means that the tasklet descriptor is inserted in one of the lists of the tasklet_vec and tasklet_hi_vec arrays. TASKLET_STATE_RUN When set, this indicates that the tasklet is being executed; on a uniprocessor system this flag is not used because there is no need to check whether a specific tasklet is running. Let's suppose you're writing a device driver and you want to use a tasklet: what has to be done? First of all, you should allocate a new tasklet_struct data structure and initialize it by invoking tasklet_init( ); this function receives as parameters the address of the tasklet descriptor, the address of your tasklet function, and its optional integer argument. Your tasklet may be selectively disabled by invoking either tasklet_disable_nosync( ) or tasklet_disable( ). Both functions increment the count field of the tasklet descriptor, but the latter function does not return until an already running instance of the tasklet function has terminated. To re-enable your tasklet, use tasklet_enable( ). To activate the tasklet, you should invoke either the tasklet_schedule( ) function or the tasklet_hi_schedule( ) function, according to the priority that you require for your tasklet. The two functions are very similar; each of them performs the following actions: 1. Checks the TASKLET_STATE_SCHED flag; if it is set, returns (the tasklet has already been scheduled) 2. Gets the logical number of the CPU that is executing the function 3. Saves the state of the IF flag and clears it to disable local interrupts 4. Adds the tasklet descriptor at the beginning of the list pointed to by tasklet_vec[cpu] or tasklet_hi_vec[cpu] 5. Invokes cpu_raise_softirq( ) to activate either the TASKLET_SOFTIRQ softirq or the HI_SOFTIRQ softirq 6. Restores the value of the IF flag saved in Step 3 (local interrupts enabled or disabled) Finally, let's see how your tasklet is executed. We know from the previous section that, once activated, softirq functions are executed by the do_softirq( ) function. The softirq function associated with the HI_SOFTIRQ softirq is named tasklet_hi_action( ), while the function associated with TASKLET_SOFTIRQ is named tasklet_action( ). Once again, the two functions are very similar; each of them: 1. Gets the logical number of the CPU that is executing the function. 2. Disables local interrupts, saving the previous state of the IF flag. 3. Stores the address of the list pointed to by tasklet_vec[cpu] or tasklet_hi_vec[cpu] in the list local variable. 4. Puts a NULL address in tasklet_vec[cpu] or tasklet_hi_vec[cpu]; thus, the list of scheduled tasklet descriptors is emptied. 5. Enables local interrupts. 6. For each tasklet descriptor in the list pointed to by list: a. In multiprocessor systems, checks the TASKLET_STATE_RUN flag of the tasklet. If it is set, a tasklet of the same type is already running on another CPU, so the function reinserts the task descriptor in the list pointed to by tasklet_vec[cpu] or tasklet_hi_vec[cpu] and activates the TASKLET_SOFTIRQ or HI_SOFTIRQ softirq again. In this way, execution of the tasklet is deferred until other tasklets of the same type are running on other CPUs. b. If the TASKLET_STATE_RUN flag is not set, the tasklet is not running on other CPUs. In multiprocessor systems, the function sets the flag so that the tasklet function cannot be executed on other CPUs. c. Checks whether the tasklet is disabled by looking at the count field of the tasklet descriptor. If it is disabled, it reinserts the task descriptor in the list pointed to by tasklet_vec[cpu] or tasklet_hi_vec[cpu]; then the function activates the TASKLET_SOFTIRQ or HI_SOFTIRQ softirq again. d. If the tasklet is enabled, clears the TASKLET_STATE_SCHED flag and executes the tasklet function. Notice that, unless the tasklet function re-activates itself, every tasklet activation triggers at most one execution of the tasklet function. 4.7.3 Bottom Halves A bottom half is essentially a high-priority tasklet that cannot be executed concurrently with any other bottom half, even if it is of a different type and on another CPU. The global_bh_lock spin lock is used to ensure that at most one bottom half is running. Linux uses an array called the bh_base table to group all bottom halves together. It is an array of pointers to bottom halves and can include up to 32 entries, one for each type of bottom half. In practice, Linux uses about half of them; the types are listed in Table 4-9. As you can see from the table, some of the bottom halves are associated with hardware devices that are not necessarily installed in the system or that are specific to platforms besides the IBM PC compatible. But TIMER_BH, TQUEUE_BH, SERIAL_BH, and IMMEDIATE_BH still see widespread use. We describe the TQUEUE_BH and IMMEDIATE_BH bottom half later in this chapter and the TIMER_BH bottom half in Chapter 6. Table 4-9. The Linux bottom halves Bottom half Peripheral device TIMER_BH Timer TQUEUE_BH Periodic task queue DIGI_BH DigiBoard PC/Xe SERIAL_BH Serial port RISCOM8_BH RISCom/8 SPECIALIX_BH Specialix IO8+ AURORA_BH Aurora multiport card (SPARC) ESP_BH Hayes ESP serial card SCSI_BH SCSI interface IMMEDIATE_BH Immediate task queue CYCLADES_BH Cyclades Cyclom-Y serial multiport CM206_BH CD-ROM Philips/LMS cm206 disk MACSERIAL_BH Power Macintosh's serial port ISICOM_BH MultiTech's ISI cards The bh_task_vec array stores 32 tasklet descriptors, one for each bottom half. During kernel initialization, these tasklet descriptors are initialized in the following way: for (i=0; i<32; ++i) tasklet_init(bh_task_vec+i, bh_action, i); As usual, before a bottom half is invoked for the first time, it must be initialized. This is done by invoking init_bh(n, routine), which inserts the routine address as the n th entry of bh_base. Conversely, remove_bh(n) removes the n th bottom half from the table. Bottom-half activation is done by invoking mark_bh( ). Since bottom halves are high- priority tasklets, mark_bh(n) just reduces to tasklet_hi_schedule(bh_task_vec + n). The bh_action( ) function is the tasklet function common to all bottom halves. It receives as a parameter the index of the bottom half and performs the following steps: 1. Gets the logical number of the CPU executing the tasklet function. 2. Checks whether the global_bh_lock spin lock has already been acquired. In this case, another CPU is running a bottom half. The function invokes mark_bh( ) to re- activate the bottom half and returns. 3. Otherwise, the function acquires the global_bh_lock spin lock so that no other bottom half can be executed in the system. 4. Checks that the local_irq_count field is set to zero (bottom halves are supposed to be run outside interrupt service routines), and that global interrupts are enabled (see Chapter 5). If one of these cases doesn't hold, the function releases the global_bh_lock spin lock and terminates. 5. Invokes the bottom half function stored in the proper entry of the bh_base array. 6. Releases the global_bh_lock spin lock and returns. 4.7.3.1 Extending a bottom half The motivation for introducing deferrable functions is to allow a limited number of functions related to interrupt handling to be executed in a deferred manner. This approach has been stretched in two directions: ● To allow not only a function that services an interrupt, but also a generic kernel function to be executed as a bottom half ● To allow several kernel functions, instead of a single one, to be associated with a bottom half Groups of functions are represented by task queues, which are lists of tq_struct structures whose fields are shown in Table 4-10. Table 4-10. The fields of the tq_struct structure Field name Description list Links for doubly linked list sync Used to prevent multiple activations routine Function to call data Argument for the function As we shall see in Chapter 13, I/O device drivers use task queues to require the execution of several related functions when a specific interrupt occurs. The DECLARE_TASK_QUEUE macro allocates a new task queue, while queue_task( ) inserts a new function in a task queue. The run_task_queue( ) function executes all the functions included in a given task queue. It's worth mentioning three particular task queues: ● The tq _immediate task queue, run by the IMMEDIATE_BH bottom half, includes kernel functions to be executed together with the standard bottom halves. The kernel invokes mark_bh( ) to activate the IMMEDIATE_BH bottom half whenever a function is added to the tq _immediate task queue. It is executed as soon as do_softirq( ) is invoked. ● The tq _timer task queue is run by the TQUEUE_BH bottom half, which is activated at every timer interrupt. As we'll see in Chapter 6, that means it runs about every 10 ms. ● The tq_context task queue is not associated with a bottom half, but it is run by the keventd kernel thread. The schedule_task( ) function adds a function to the task queue; its execution is deferred until the scheduler selects the keventd kernel thread as the next process to run. The main advantage of tq_context, with respect to the other task queues based on deferrable functions, is that its functions can freely perform blocking operations. On the other hand, softirqs (and therefore tasklets and bottom halves) are similar to interrupt handlers in that kernel developers cannot make any assumption on the process that will execute the deferrable functions. From a practical point of view, this means that softirqs cannot perform blocking operations like accessing a file, acquiring a semaphore, or sleeping in a wait queue. The price to pay is that, once scheduled for execution in tq_context, a function might be delayed for quite a long time interval. I l@ve RuBoard I l@ve RuBoard 4.8 Returning from Interrupts and Exceptions We will finish the chapter by examining the termination phase of interrupt and exception handlers. Although the main objective is clear — namely, to resume execution of some program — several issues must be considered before doing it: Number of kernel control paths being concurrently executed If there is just one, the CPU must switch back to User Mode. Pending process switch requests If there is any request, the kernel must perform process scheduling; otherwise, control is returned to the current process. Pending signals If a signal is sent to the current process, it must be handled. The kernel assembly language code that accomplishes all these things is not, technically speaking, a function, since control is never returned to the functions that invoke it. It is a piece of code with four different entry points called ret_from_intr, ret_from_exception, ret_from_sys_call, and ret_from_fork. We will refer to it as four different functions since this makes the description simpler, and we shall refer quite often to the following three entry points as functions: ret_from_exception( ) Terminates all exceptions except the 0x80 ones ret_from_intr( ) Terminates interrupt handlers ret_from_sys_call( ) Terminates system calls (i.e., kernel control paths engendered by 0x80 programmed exceptions) ret_from_fork( ) Terminates the fork( ), vfork( ), or clone( ) system calls (child only). The general flow diagram with the corresponding four entry points is illustrated in Figure 4- 5. The ret_from_exception( ) and ret_from_intr( ) entry points look the same in the picture, but they aren't. In the former case, the kernel knows the descriptor of the process that caused the exception; in the latter case, no process descriptor is associated with the interrupt. Besides the labels corresponding to the entry points, a few others have been added to allow you to relate the assembly language code more easily to the flow diagram. Let's now examine in detail how the termination occurs in each case. Figure 4-5. Returning from interrupts and exceptions 4.8.1 The ret_ from_exception( ) Function The ret_from_exception( ) function is essentially equivalent to the following assembly language code: ret_from_exception: movl 0x30(%esp),%eax movb 0x2C(%esp),%al testl $(0x000200003),%eax jne ret_from_sys_call restore_all: popl %ebx popl %ecx popl %edx popl %esi popl %edi popl %ebp popl %eax popl %ds popl %es addl $4,%esp iret The values of the cs and eflags registers, which were pushed on the stack when the exception occurred, are used by the function to determine whether the interrupted program was running in User Mode or if the VM flag of eflags was set.[15] In either case, a jump is made to the ret_from_sys_call( ) function. Otherwise, the interrupted kernel control path is to be restarted. The function loads the registers with the values saved by the SAVE_ALL macro when the exception started, and the function yields control to the interrupted program by executing the iret instruction. [15] This flag allows programs to be executed in Virtual-8086 Mode; see the Pentium manuals for more details. 4.8.2 The ret_ from_intr( ) Function The ret_from_intr( ) function is essentially equivalent to ret_from_exception( ): ret_from_intr: movl $0xffffe000,%ebx andl %esp,%ebx jmp ret_from_exception Before invoking ret_from_exception( ), ret_from_intr( ) loads in the ebx register the address of the current's process descriptor (see Section 3.2.2). This is necessary because the ret_from_sys_call( ) function, which can be invoked by ret_from_exception( ), expects to find that address in ebx. On the other hand, when ret_from_exception( ) starts, the ebx register has already been loaded with current's address by the exception handler (see Section 4.5.1 earlier in this chapter). 4.8.3 The ret_ from_sys_call( ) Function The ret_from_sys_call( ) function is equivalent to the following assembly language code: ret_from_sys_call: cli cmpl $0,20(%ebx) jne reschedule cmpl $0,8(%ebx) jne signal_return jmp restore_all As we said previously, the ebx register points to the current process descriptor; within that descriptor, the need_resched field is at offset 20, which is checked by the first cmpl instruction. Therefore, if the need_resched field is 1, the schedule( ) function is invoked to perform a process switch: reschedule: call schedule jmp ret_from_sys_call The offset of the sigpending field inside the process descriptor is 8. If it is null, current resumes execution in User Mode by restoring the hardware context of the process saved on the stack. Otherwise, the function jumps to signal_return to process the pending signals of current: signal_return: sti testl $(0x00020000),0x30(%esp) movl %esp,%eax jne v86_signal_return xorl %edx,%edx call do_signal jmp restore_all v86_signal_return: call save_v86_state movl %eax,%esp xorl %edx,%edx call do_signal jmp restore_all If the interrupted process was in VM86 mode, the save_v86_state( ) function is invoked. The do_signal( ) function (see Chapter 10) is then invoked to handle the pending signals. Finally, current can resume execution in User Mode. 4.8.4 The ret_ from_ fork( ) Function The ret_from_fork( ) function is executed by the child process right after its creation through a fork( ), vfork( ), or clone( ) system call (see Section 3.4.1). It is essentially equivalent to the following assembly language code: ret_from_fork: pushl %ebx call schedule_tail addl $4,%esp movl $0xffffe000,%ebx andl %esp,%ebx testb $0x02,24(%ebx) jne tracesys_exit jmp ret_from_sys_call tracesys_exit: call syscall_trace jmp ret_from_sys_call Initially, the ebx register stores the address of the parent's process descriptor; this value is passed to the schedule_tail( ) function as a parameter (see Chapter 11). When that function returns, ebx is reloaded with the current's process descriptor address. Then the ret_from_fork( ) function checks the value of the ptrace field of the current (at offset 24 of the process descriptor). If the field is not null, the fork( ), vfork( ), or clone( ) system call is traced, so the syscall_trace( ) function is invoked to notify the debugging process. We give more details on system call tracing in Chapter 9. I l@ve RuBoard I l@ve RuBoard Chapter 5. Kernel Synchronization You could think of the kernel as a server that answers requests; these requests can come either from a process running on a CPU or an external device issuing an interrupt request. We make this analogy to underscore that parts of the kernel are not run serially, but in an interleaved way. Thus, they can give rise to race conditions, which must be controlled through proper synchronization techniques. A general introduction to these topics can be found in Section 1.6. We start this chapter by reviewing when, and to what extent, kernel requests are executed in an interleaved fashion. We then introduce the basic synchronization primitives implemented by the kernel and describe how they are applied in the most common cases. Finally we illustrate a few practical examples. I l@ve RuBoard I l@ve RuBoard 5.1 Kernel Control Paths In Section 4.3, a kernel control path was defined as a sequence of instructions executed by the kernel to handle interrupts of different kinds. Each kernel request is handled by a different kernel control path, which usually executes several different kernel functions. For example, when a User Mode process issues a system call request, the system_call( ) function (see Chapter 9) begins this particular kernel control path and the ret_from_sys_call( ) function ends it (see Section 4.8). As we said, kernel requests may be issued in several possible ways: ● A process executing in User Mode causes an exception — for instance, by executing an int 0x80 assembly language instruction. ● An external device sends a signal to a Programmable Interrupt Controller by using an IRQ line, and the corresponding interrupt is enabled. ● A process executing in Kernel Mode causes a Page Fault exception (see Section 8.4). ● A process running in a multiprocessor system and executing in Kernel Mode raises an interprocessor interrupt (see Section 4.6.2). Kernel control paths play a role similar to that of processes, except they are much more rudimentary. First, a descriptor is not attached to them; second, they are not scheduled through a single function, but rather by inserting sequences of instructions that stop or resume the paths into the kernel code. In the simplest cases, the CPU executes a kernel control path sequentially from the first instruction to the last. However, the CPU interleaves kernel control paths when one of the following events happens: ● A process switch occurs. As we shall see in Chapter 11, a process switch can occur only when the schedule( ) function is invoked. ● An interrupt occurs while the CPU is running a kernel control path with interrupts enabled. In this case, the first kernel control path is left unfinished and the CPU starts processing another kernel control path to handle the interrupt. ● A deferrable function is executed. As we explained in Section 4.7.1, deferrable functions can be triggered by several events, such as interrupt occurrences or invocations of the local_bh_enable( ) function. It is important to interleave kernel control paths to implement multiprocessing. In addition, as already noted in Section 4.3, interleaving improves the throughput of programmable interrupt controllers and device controllers. While interleaving kernel control paths, special care must be applied to data structures that contain several related member variables — for instance, a buffer and an integer indicating its length. All statements affecting such a data structure must be put into a single critical section; otherwise, the data structure is in danger of being corrupted. I l@ve RuBoard I l@ve RuBoard 5.2 When Synchronization Is Not Necessary As already pointed out, the Linux kernel is not preemptive — that is, a running process cannot be preempted (replaced by a higher-priority process) while it remains in Kernel Mode. In particular, the following assertions always hold in Linux: ● No process running in Kernel Mode may be replaced by another process, except when the former voluntarily relinquishes control of the CPU.[1] [1] Of course, all process switches are performed in Kernel Mode. However, a process switch may occur only when the current process is going to return in User Mode. ● Interrupt, exception, or softirq handling can interrupt a process running in Kernel Mode; however, when the handler terminates, the kernel control path of the process is resumed. ● A kernel control path performing interrupt handling cannot be interrupted by a kernel control path executing a deferrable function or a system call service routine. Thanks to these assertions, on uniprocessor systems kernel control paths dealing with nonblocking system calls are atomic with respect to other control paths started by system calls. This simplifies the implementation of many kernel functions: any kernel data structures that are not updated by interrupt, exception, or softirq handlers can be safely accessed. However, if a process in Kernel Mode voluntarily relinquishes the CPU, it must ensure that all data structures are left in a consistent state. Moreover, when it resumes its execution, it must recheck the value of all previously accessed data structures that could be changed. The change could be caused by a different kernel control path, possibly running the same code on behalf of a separate process. As you would expect, things are much more complicated in multiprocessor systems. Many CPUs may execute kernel code at the same time, so kernel developers cannot assume that a data structure can be safely accessed just because it is never touched by an interrupt, exception, or softirq handler. The rest of this chapter describes what to do when synchronization is necessary — i.e., how to prevent data corruption due to unsafe accesses to shared data structures. I l@ve RuBoard I l@ve RuBoard 5.3 Synchronization Primitives Chapter 1 introduced the concepts of race condition and critical region for processes. The same definitions apply to kernel control paths. In this chapter, a race condition can occur when the outcome of a computation depends on how two or more interleaved kernel control paths are nested. A critical region is any section of code that must be completely executed by any kernel control path that enters it before another kernel control path can enter it. We now examine how kernel control paths can be interleaved while avoiding race conditions among shared data. Table 5-1 lists the synchronization techniques used by the Linux kernel. The "Applies to" column indicates whether the synchronization technique applies to all CPUs in the system or to a single CPU. For instance, local interrupts disabling applies to just one CPU (other CPUs in the system are not affected); conversely, an atomic operation affects all CPUs in the system (atomic operations on several CPUs cannot interleave while accessing the same data structure). Table 5-1. Various types of synchronization techniques used by the kernel Technique Description Scope Atomic operation Atomic read-modify-write instruction to a counter All CPUs Memory barrier Avoid instruction re-ordering Local CPU Spin lock Lock with busy wait All CPUs Semaphore Lock with blocking wait (sleep) All CPUs Local interrupt disabling Forbid interrupt handling on a single CPU Local CPU Local softirq disabling Forbid deferrable function handling on a single CPU Local CPU Global interrupt disabling Forbid interrupt and softirq handling on all CPUs All CPUs Let's now briefly discuss each synchronization technique. In the later section Section 5.4, we show how these synchronization techniques can be combined to effectively protect kernel data structures. 5.3.1 Atomic Operations Several assembly language instructions are of type "read-modify-write" — that is, they access a memory location twice, the first time to read the old value and the second time to write a new value. Suppose that two kernel control paths running on two CPUs try to "read-modify-write" the same memory location at the same time by executing nonatomic operations. At first, both CPUs try to read the same location, but the memory arbiter (a hardware circuit that serializes accesses to the RAM chips) steps in to grant access to one of them and delay the other. However, when the first read operation has completed, the delayed CPU reads exactly the same (old) value from the memory location. Both CPUs then try to write the same (new) value on the memory location; again, the bus memory access is serialized by the memory arbiter, and eventually both write operations succeed. However, the global result is incorrect because both CPUs write the same (new) value. Thus, the two interleaving "read-modify- write" operations act as a single one. The easiest way to prevent race conditions due to "read-modify-write" instructions is by ensuring that such operations are atomic at the chip level. Any such operation must be executed in a single instruction without being interrupted in the middle and avoiding accesses to the same memory location by other CPUs. These very small atomic operations can be found at the base of other, more flexible mechanisms to create critical sections. Let's review 80 x 86 instructions according to that classification. ● Assembly language instructions that make zero or one aligned memory access are atomic.[2] [2] A data item is aligned in memory when its address is a multiple of its size in bytes. For instance, the address of an aligned short integer must be a multiple of two, while the address of an aligned integer must be a multiple of four. Generally speaking, a unaligned memory access is not atomic. ● Read-modify-write assembly language instructions (such as inc or dec) that read data from memory, update it, and write the updated value back to memory are atomic if no other processor has taken the memory bus after the read and before the write. Memory bus stealing never happens in a uniprocessor system. ● Read-modify-write assembly language instructions whose opcode is prefixed by the lock byte (0xf0) are atomic even on a multiprocessor system. When the control unit detects the prefix, it "locks" the memory bus until the instruction is finished. Therefore, other processors cannot access the memory location while the locked instruction is being executed. ● Assembly language instructions (whose opcode is prefixed by a rep byte (0xf2, 0xf3), which forces the control unit to repeat the same instruction several times) are not atomic. The control unit checks for pending interrupts before executing a new iteration. When you write C code, you cannot guarantee that the compiler will use a single, atomic instruction for an operation like a=a+1 or even for a++. Thus, the Linux kernel provides a special atomic_t type (a 24-bit atomically accessible counter) and some special functions (see Table 5-2) that act on atomic_t variables and are implemented as single, atomic assembly language instructions. On multiprocessor systems, each such instruction is prefixed by a lock byte. Table 5-2. Atomic operations in Linux Function Description atomic_read(v) Return *v atomic_set(v,i) Set *v to i atomic_add(i,v) Add i to *v atomic_sub(i,v) Subtract i from *v atomic_sub_and_test(i, v) Subtract i from *v and return 1 if the result is zero; 0 otherwise atomic_inc(v) Add 1 to *v atomic_dec(v) Subtract 1 from *v atomic_dec_and_test(v) Subtract 1 from *v and return 1 if the result is zero; 0 otherwise atomic_inc_and_test(v) Add 1 to *v and return 1 if the result is zero; 0 otherwise atomic_add_negative(i, v) Add i to *v and return 1 if the result is negative; 0 otherwise Another class of atomic functions operate on bit masks (see Table 5-3). In this case, a bit mask is a generic integer variable. Table 5-3. Atomic bit handling functions in Linux Function Description test_bit(nr, addr) Return the value of the nrth bit of *addr set_bit(nr, addr) Set the nrth bit of *addr clear_bit(nr, addr) Clear the nrth bit of *addr change_bit(nr, addr) Invert the nrth bit of *addr test_and_set_bit(nr, addr) Set the nrth bit of *addr and return its old value test_and_clear_bit(nr, addr) Clear the nrth bit of *addr and return its old value test_and_change_bit(nr, addr) Invert the nrth bit of *addr and return its old value atomic_clear_mask(mask, addr) Clear all bits of addr specified by mask atomic_set_mask(mask, addr) Set all bits of addr specified by mask 5.3.2 Memory Barriers When using optimizing compilers, you should never take for granted that instructions will be performed in the exact order in which they appear in the source code. For example, a compiler might reorder the assembly language instructions in such a way to optimize how registers are used. Moreover, modern CPUs usually execute several instructions in parallel, and might reorder memory accesses. These kinds of reordering can greatly speed up the program. When dealing with synchronization, however, instructions reordering must be avoided. As a matter of fact, all synchronization primitives act as memory barriers. Things would quickly become hairy if an instruction placed after a synchronization primitive is executed before the synchronization primitive itself. A memory barrier primitive ensures that the operations placed before the primitive are finished before starting the operations placed after the primitive. Thus, a memory barrier is like a firewall that cannot be passed by any assembly language instruction. In the 80 x 86 processors, the following kinds of assembly language instructions are said to be "serializing" because they act as memory barriers: ● All instructions that operate on I/O ports ● All instructions prefixed by the lock byte (see Section 5.3.1) ● All instructions that write into control registers, system registers, or debug registers (for instance, cli and sti, which change the status of the IF flag in the eflags register) ● A few special assembly language instructions; among them, the iret instruction that terminates an interrupt or exception handler Linux uses six memory barrier primitives, which are shown in Table 5-4. "Read memory barriers" act only on instructions that read from memory, while "write memory barriers" act only on instructions that write to memory. Memory barriers can be useful both in multiprocessor systems and in uniprocessor systems. The smp_xxx( ) primitives are used whenever the memory barrier should prevent race conditions that might occur only in multiprocessor systems; in uniprocessor systems, they do nothing. The other memory barriers are used to prevent race conditions occurring both in uniprocessor and multiprocessor systems. Table 5-4. Memory barriers in Linux Macro Description mb( ) Memory barrier for MP and UP rmb( ) Read memory barrier for MP and UP wmb( ) Write memory barrier for MP and UP smp_mb( ) Memory barrier for MP only smp_rmb( ) Read memory barrier for MP only smp_wmb( ) Write memory barrier for MP only The implementations of the memory barrier primitives depend on the architecture of the system. For instance, on the Intel platform, the rmb( ) macro expands into asm volatile("lock;addl $0,0(%%esp)":::"memory"). The asm instruction tells the compiler to insert some assembly language instructions. The volatile keyword forbids the compiler to reshuffle the asm instruction with the other instructions of the program. The memory keyword forces the compiler to assume that all memory locations in RAM have been changed by the assembly language instruction; therefore, the compiler cannot optimize the code by using the values of memory locations stored in CPU registers before the asm instruction. Finally, the lock;addl $0,0(%%esp) assembly language instruction adds zero to the memory location on top of the stack; the instruction is useless by itself, but the lock prefix makes the instruction a memory barrier for the CPU. The wmb( ) macro on Intel is actually simpler because it expands into asm volatile("":::"memory"). This is because Intel processors never reorder write memory accesses, so there is no need to insert a serializing assembly language instruction in the code. The macro, however, forbids the compiler to reshuffle the instructions. Notice that in multiprocessor systems, all atomic operations described in the earlier section Section 5.3.1 act as memory barriers because they use the lock byte. 5.3.3 Spin Locks A widely used synchronization technique is locking. When a kernel control path must access a shared data structure or enter a critical region, it needs to acquire a "lock" for it. A resource protected by a locking mechanism is quite similar to a resource confined in a room whose door is locked when someone is inside. If a kernel control path wishes to access the resource, it tries to "open the door" by acquiring the lock. It succeeds only if the resource is free. Then, as long as it wants to use the resource, the door remains locked. When the kernel control path releases the lock, the door is unlocked and another kernel control path may enter the room. Figure 5-1 illustrates the use of locks. Five kernel control paths (P0, P1, P2, P3, and P4) are trying to access two critical regions (C1 and C2). Kernel control path P0 is inside C1, while P2 and P4 are waiting to enter it. At the same time, P1 is inside C2, while P3 is waiting to enter it. Notice that P0 and P1 could run concurrently. The lock for critical region C3 is open since no kernel control path needs to enter it. Figure 5-1. Protecting critical regions with several locks Spin locks are a special kind of lock designed to work in a multiprocessor environment. If the kernel control path finds the spin lock "open," it acquires the lock and continues its execution. Conversely, if the kernel control path finds the lock "closed" by a kernel control path running on another CPU, it "spins" around, repeatedly executing a tight instruction loop, until the lock is released. Of course, spin locks are useless in a uniprocessor environment, since the waiting kernel control path would keep running, so the kernel control path that is holding the lock would not have any chance to release it. The instruction loop of spin locks represents a "busy wait." The waiting kernel control path keeps running on the CPU, even if it has nothing to do besides waste time. Nevertheless, spin locks are usually very convenient, since many kernel resources are locked for a fraction of a millisecond only; therefore, it would be far more time-consuming to release the CPU and reacquire it later. In Linux, each spin lock is represented by a spinlock_t structure consisting of a single lock field; the value 1 corresponds to the unlocked state, while any negative value and zero denote the locked state. Five functions shown in Table 5-5 are used to initialize, test, and set spin locks. On uniprocessor systems, none of these functions do anything, except for spin_trylock( ), which always returns 1. All these functions are based on atomic operations; this ensures that the spin lock will be properly updated by a process running on a CPU even if other processes running on different CPUs attempt to modify the spin lock at the same time.[3] [3] Spin locks, ironically enough, are global and therefore must themselves be protected against concurrent accesses. Table 5-5. Spin lock functions Function Description spin_lock_init( ) Set the spin lock to 1 (unlocked) spin_lock( ) Cycle until spin lock becomes 1 (unlocked), then set it to 0 (locked) spin_unlock( ) Set the spin lock to 1 (unlocked) spin_unlock_wait( ) Wait until the spin lock becomes 1 (unlocked) spin_is_locked( ) Return 0 if the spin lock is set to 1 (unlocked); 0 otherwise spin_trylock( ) Set the spin lock to 0 (locked), and return 1 if the lock is obtained; 0 otherwise Let's discuss in detail the spin_lock macro, which is used to acquire a spin lock. It takes the address slp of the spin lock as its parameter and yields essentially the following assembly language code:[4] [4] The actual implementation of spin_lock is slightly more complicated. The code at label 2, which is executed only if the spin lock is busy, is included in an auxiliary section so that in the most frequent case (free spin lock) the hardware cache is not filled with code that won't be executed. In our discussion, we omit these optimization details. 1: lock; decb slp jns 3f 2: cmpb $0,slp pause jle 2b jmp 1b 3: The decb assembly language instruction decrements the spin lock value; the instruction is atomic because it is prefixed by the lock byte. A test is then performed on the sign flag. If it is clear, it means that the spin lock was set to 1 (unlocked), so normal execution continues at label 3 (the f suffix denotes the fact that the label is a "forward" one; it appears in a later line of the program). Otherwise, the tight loop at label 2 (the b suffix denotes a "backward" label) is executed until the spin lock assumes a positive value. Then execution restarts from label 1, since it is unsafe to proceed without checking whether another processor has grabbed the lock. The pause assembly language instruction, which was introduced in the Pentium 4 model, is designed to optimize the execution of spin lock loops. By introducing a small delay, it speeds up the execution of code following the lock and reduces power consumption. The pause instruction is backward compatible with earlier models of Intel processors because it corresponds to the instructions rep;nop, which essentially do nothing. The spin_unlock macro releases a previously acquired spin lock; it essentially yields the following code: lock; movb $1, slp Again, the lock byte ensures that the loading instruction is atomic. 5.3.4 Read/Write Spin Locks Read/write spin locks have been introduced to increase the amount of concurrency inside the kernel. They allow several kernel control paths to simultaneously read the same data structure, as long as no kernel control path modifies it. If a kernel control path wishes to write to the structure, it must acquire the write version of the read/write lock, which grants exclusive access to the resource. Of course, allowing concurrent reads on data structures improves system performance. Figure 5-2 illustrates two critical regions (C1 and C2) protected by read/write locks. Kernel control paths R0 and R1 are reading the data structures in C1 at the same time, while W0 is waiting to acquire the lock for writing. Kernel control path W1 is writing the data structures in C2, while both R2 and W2 are waiting to acquire the lock for reading and writing, respectively. Figure 5-2. Read/write spin locks Each read/write spin lock is a rwlock_t structure; its lock field is a 32-bit field that encodes two distinct pieces of information: ● A 24-bit counter denoting the number of kernel control paths currently reading the protected data structure. The two's complement value of this counter is stored in bits 0-23 of the field. ● An unlock flag that is set when no kernel control path is reading or writing, and clear otherwise. This unlock flag is stored in bit 24 of the field. Notice that the lock field stores the number 0x01000000 if the spin lock is idle (unlock flag set and no readers), the number 0x00000000 if it has been acquired for writing (unlock flag clear and no readers), and any number in the sequence 0x00ffffff, 0x00fffffe, and so on, if it has been acquired for reading by one, two, and more processes (unlock flag clear and the two's complement on 24 bits of the number of readers). The rwlock_init macro initializes the lock field of a read/write spin lock to 0x01000000 (unlocked). 5.3.4.1 Getting and releasing a lock for reading The read_lock macro, applied to the address rwlp of a read/write spin lock, essentially yields the following code: movl $rwlp,%eax lock; subl $1,(%eax) jns 1f call _ _read_lock_failed 1: where _ _read_lock_failed( ) is the following assembly language function: _ _read_lock_failed: lock; incl (%eax) 1: cmpl $1,(%eax) js 1b lock; decl (%eax) js _ _read_lock_failed ret The read_lock macro atomically decreases the spin lock value by 1, thus incrementing the number of readers. The spin lock is acquired if the decrement operation yields a nonnegative value; otherwise, the _ _read_lock_failed( ) function is invoked. The function atomically increments the lock field to undo the decrement operation performed by the read_lock macro, and then loops until the field becomes positive (greater than or equal to 1). Next, _ _read_lock_failed( ) tries to get the spin lock again (another kernel control path could acquire the spin lock for writing right after the cmpl instruction). Releasing the read lock is quite simple because the read_unlock macro must simply increment the counter in the lock field to decrease the number of readers; thus, the macro yields the following assembly language instruction: lock; incl rwlp 5.3.4.2 Getting and releasing a lock for writing The write_lock function applied to the address rwlp of a read/write spin lock yields the following instructions: movl $rwlp,%eax lock; subl $0x01000000,(%eax) jz 1f call _ _write_lock_failed 1: where _ _write_lock_failed( ) is the following assembly language function: _ _write_lock_failed: lock; addl $0x01000000,(%eax) 1: cmpl $0x01000000,(%eax) jne 1b lock; subl $0x01000000,(%eax) jnz _ _write_lock_failed ret The write_lock macro atomically subtracts 0x01000000 from the spin lock value, thus clearing the unlock flag. The spin lock is acquired if the subtraction operation yields zero (no readers); otherwise, the _ _write_lock_failed( ) function is invoked. This function atomically adds 0x01000000 to the lock field to undo the subtraction operation performed by the write_lock macro, and then loops until the spin lock becomes idle (lock field equal to 0x01000000). Next, _ _write_lock_failed( ) tries to get the spin lock again (another kernel control path could acquire the spin lock right after the cmpl instruction). Once again, releasing the write lock is much simpler because the write_unlock macro must simply set the unlock flag in the lock field. Thus, the macro yields the following assembly language instruction: lock; addl $0x01000000,rwlp 5.3.5 The Big Reader Lock Read/write spin locks are useful for data structures that are accessed by many readers and a few writers. They are more convenient than normal spin locks because they allow several readers to concurrently access the protected data structure. However, any time a CPU acquires a read/write spin lock, the counter in rwlock_t must be updated. A further access to the rwlock_t data structure performed by another CPU incurs in a significant performance penalty because the hardware caches of the two processors must be synchronized. Even worse, the new CPU changes the rwlock_t data structure, so the cache of the former CPU becomes invalid and there is another performance penalty when the former CPU releases the lock. In short, reader CPUs are playing ping-pong with the cache line containing the read/write spin lock data structure. A special type of read/write spin locks, named big reader read/write spin locks, was designed to address this problem. The idea is to split the "reader" portion of the lock across all CPUs, so that each per-CPU data structure lies in its own line of the hardware caches. Readers do not need to stomp one another, so no reader CPU "snoops" the reader lock of another CPU. Conversely, the "writer" portion of the lock is common to all CPUs because only one CPU can acquire the lock for writing. The _ _brlock_array array stores the "reader" portions of the big reader read/write spin locks; for every such lock, and for every CPU in the system, the array includes a lock flag, which is set to 1 when the lock is closed for reading by the corresponding CPU. Conversely, the _ _br_write_locks array stores the "writer" portions of the big reader spin locks — that is, a normal spin lock that is set when the big reader spin lock has been acquired for writing. The br_read_lock( ) function acquires the spin lock for reading. It just sets the lock flag in _ _brlock_array corresponding to the executing CPU and the big reader spin lock to 1, and then waits until the spin lock in _ _br_write_locks is open. Conversely, the br_read_unlock( ) function simply clears the lock flag in _brlock_array. The br_write_lock( ) function acquires the spin lock for writing. It invokes spin_lock to get the spin lock in _ _br_write_locks corresponding to the big reader spin lock, and then checks that all lock flags in _ _brlock_array corresponding to the big reader lock are cleared; if not, it releases the spin lock in _ _br_write_locks and starts again. The br_write_unlock( ) function simply invokes spin_unlock to release the spin lock in _ _br_write_locks. As you may notice, acquiring an open big reader spin lock for reading is really fast, but acquiring it for writing is very slow because the CPU must acquire a spin lock and check several lock flags. Thus, big reader spin locks are rarely used. On the Intel architecture, there is just one big reader spin lock, used in the networking code. 5.3.6 Semaphores We have already introduced semaphores in Section 1.6.5. Essentially, they implement a locking primitive that allows waiters to sleep until the desired resource becomes free. Actually, Linux offers two kinds of semaphores: ● Kernel semaphores, which are used by kernel control paths ● System V IPC semaphores, which are used by User Mode processes In this section, we focus on kernel semaphores, while IPC semaphores are described in Chapter 19. A kernel semaphore is similar to a spin lock, in that it doesn't allow a kernel control path to proceed unless the lock is open. However, whenever a kernel control path tries to acquire a busy resource protected by a kernel semaphore, the corresponding process is suspended. It becomes runnable again when the resource is released. Therefore, kernel semaphores can be acquired only by functions that are allowed to sleep; interrupt handlers and deferrable functions cannot use them. A kernel semaphore is an object of type struct semaphore, containing the fields shown in the following list. count Stores an atomic_t value. If it is greater than 0, the resource is free — that is, it is currently available. If count is equal to 0, the semaphore is busy but no other process is waiting for the protected resource. Finally, if count is negative, the resource is unavailable and at least one process is waiting for it. wait Stores the address of a wait queue list that includes all sleeping processes that are currently waiting for the resource. Of course, if count is greater than or equal to 0, the wait queue is empty. sleepers Stores a flag that indicates whether some processes are sleeping on the semaphore. We'll see this field in operation soon. The init_MUTEX and init_MUTEX_LOCKED macros may be used to initialize a semaphore for exclusive access: they set the count field to 1 (free resource with exclusive access) and 0 (busy resource with exclusive access currently granted to the process that initializes the semaphore). Note that a semaphore could also be initialized with an arbitrary positive value n for count. In this case, at most n processes are allowed to concurrently access the resource. 5.3.6.1 Getting and releasing semaphores Let's start by discussing how to release a semaphore, which is much simpler than getting one. When a process wishes to release a kernel semaphore lock, it invokes the up( ) assembly language function. This function is essentially equivalent to the following code: movl $sem,%ecx lock; incl (%ecx) jg 1f pushl %eax pushl %edx pushl %ecx call _ _up popl %ecx popl %edx popl %eax 1: where _ _up( ) is the following C function: void _ _up(struct semaphore *sem) { wake_up(&sem->wait); } The up( ) function increments the count field of the *sem semaphore (at offset 0 of the semaphore structure), and then it checks whether its value is greater than 0. The increment of count and the setting of the flag tested by the following jump instruction must be atomically executed; otherwise, another kernel control path could concurrently access the field value, with disastrous results. If count is greater than 0, there was no process sleeping in the wait queue, so nothing has to be done. Otherwise, the _ _up( ) function is invoked so that one sleeping process is woken up. Conversely, when a process wishes to acquire a kernel semaphore lock, it invokes the down( ) function. The implementation of down( ) is quite involved, but it is essentially equivalent to the following: down: movl $sem,%ecx lock; decl (%ecx); jns 1f pushl %eax pushl %edx pushl %ecx call _ _down popl %ecx popl %edx popl %eax 1: where _ _down( ) is the following C function: void _ _down(struct semaphore * sem) { DECLARE_WAITQUEUE(wait, current); current->state = TASK_UNINTERRUPTIBLE; add_wait_queue_exclusive(&sem->wait, &wait); spin_lock_irq(&semaphore_lock); sem->sleepers++; for (;;) { if (!atomic_add_negative(sem->sleepers-1, &sem->count)) { sem->sleepers = 0; break; } sem->sleepers = 1; spin_unlock_irq(&semaphore_lock); schedule( ); current->state = TASK_UNINTERRUPTIBLE; spin_lock_irq(&semaphore_lock); } spin_unlock_irq(&semaphore_lock); remove_wait_queue(&sem->wait, &wait); current->state = TASK_RUNNING; wake_up(&sem->wait); } The down( ) function decrements the count field of the *sem semaphore (at offset 0 of the semaphore structure), and then checks whether its value is negative. Again, the decrement and the test must be atomically executed. If count is greater than or equal to 0, the current process acquires the resource and the execution continues normally. Otherwise, count is negative and the current process must be suspended. The contents of some registers are saved on the stack, and then _ _down( ) is invoked. Essentially, the _ _down( ) function changes the state of the current process from TASK_RUNNING to TASK_UNINTERRUPTIBLE, and puts the process in the semaphore wait queue. Before accessing other fields of the semaphore structure, the function also gets the semaphore_lock spin lock and disables local interrupts. This ensures that no process running on another CPU is able to read or modify the fields of the semaphore while the current process is updating them. The main task of the _ _down( ) function is to suspend the current process until the semaphore is released. However, the way in which this is done is quite involved. To easily understand the code, keep in mind that the sleepers field of the semaphore is usually set to 0 if no process is sleeping in the wait queue of the semaphore, and it is set to 1 otherwise. Let's try to explain the code by considering a few typical cases. MUTEX semaphore open (count equal to 1, sleepers equal to 0) The down macro just sets the count field to 0 and jumps to the next instruction of the main program; therefore, the _ _down( ) function is not executed at all. MUTEX semaphore closed, no sleeping processes (count equal to 0, sleepers equal to 0) The down macro decrements count and invokes the _ _down( ) function with the count field set to -1 and the sleepers field set to 0. In each iteration of the loop, the function checks whether the count field is negative. (Observe that the count field is not changed by atomic_add_negative( ) because sleepers is equal to 0 when the function is invoked.) ❍ If the count field is negative, the function invokes schedule( ) to suspend the current process. The count field is still set to -1, and the sleepers field to 1. The process picks up its run subsequently inside this loop and issues the test again. ❍ If the count field is not negative, the function sets sleepers to 0 and exits from the loop. It tries to wake up another process in the semaphore wait queue (but in our scenario, the queue is now empty), and terminates holding the semaphore. On exit, both the count field and the sleepers field are set to 0, as required when the semaphore is closed but no process is waiting for it. MUTEX semaphore closed, other sleeping processes (count equal to -1, sleepers equal to 1) The down macro decrements count and invokes the _ _down( ) function with count set to -2 and sleepers set to 1. The function temporarily sets sleepers to 2, and then undoes the decrement performed by the down macro by adding the value sleepers-1 to count. At the same time, the function checks whether count is still negative (the semaphore could have been released by the holding process right before _ _down( ) entered the critical region). ❍ If the count field is negative, the function resets sleepers to 1 and invokes schedule( ) to suspend the current process. The count field is still set to - 1, and the sleepers field to 1. ❍ If the count field is not negative, the function sets sleepers to 0, tries to wake up another process in the semaphore wait queue, and exits holding the semaphore. On exit, the count field is set to 0 and the sleepers field to 0. The values of both fields look wrong, because there are other sleeping processes. However, consider that another process in the wait queue has been woken up. This process does another iteration of the loop; the atomic_add_negative( ) function subtracts 1 from count, restoring it to - 1; moreover, before returning to sleep, the woken-up process resets sleepers to 1. As you may easily verify, the code properly works in all cases. Consider that the wake_up( ) function in _ _down( ) wakes up at most one process because the sleeping processes in the wait queue are exclusive (see Section 3.2.4). Only exception handlers, and particularly system call service routines, can use the down( ) function. Interrupt handlers or deferrable functions must not invoke down( ), since this function suspends the process when the semaphore is busy.[5] For this reason, Linux provides the down_trylock( ) function, which may be safely used by one of the previously mentioned asynchronous functions. It is identical to down( ) except when the resource is busy. In this case, the function returns immediately instead of putting the process to sleep. [5] Exception handlers can block on a semaphore. Linux takes special care to avoid the particular kind of race condition in which two nested kernel control paths compete for the same semaphore; if that happens, one of them waits forever because the other cannot run and free the semaphore. A slightly different function called down_interruptible( ) is also defined. It is widely used by device drivers since it allows processes that receive a signal while being blocked on a semaphore to give up the "down" operation. If the sleeping process is woken up by a signal before getting the needed resource, the function increments the count field of the semaphore and returns the value -EINTR. On the other hand, if down_interruptible( ) runs to normal completion and gets the resource, it returns 0. The device driver may thus abort the I/O operation when the return value is -EINTR. Finally, since processes usually find semaphores in an open state, the semaphore functions are optimized for this case. In particular, the up( ) function does not enter in a critical region if the semaphore wait queue is empty; similarly, the down( ) function does not enter in a critical region if the semaphore is open. Much of the complexity of the semaphore implementation is precisely due to the effort of avoiding costly instructions in the main branch of the execution flow. 5.3.7 Read/Write Semaphores Read/write semaphores are a new feature of Linux 2.4. They are similar to the read/write spin locks described earlier in Section 5.3.4, except that waiting processes are suspended until the semaphore becomes open again. Many kernel control paths may concurrently acquire a read/write semaphore for reading; however, any writer kernel control path must have exclusive access to the protected resource. Therefore, the semaphore can be acquired for writing only if no other kernel control path is holding it for either read or write access. Read/write semaphores improve the amount of concurrency inside the kernel and improve overall system performance. The kernel handles all processes waiting for a read/write semaphore in strict FIFO order. Each reader or writer that finds the semaphore closed is inserted in the last position of a semaphore's wait queue list. When the semaphore is released, the processes in the first positions of the wait queue list is checked. The first process is always awoken. If it is a writer, the other processes in the wait queue continue to sleep. If it is a reader, any other reader following the first process is also woken up and gets the lock. However, readers that have been queued after a writer continue to sleep. Each read/write semaphore is described by a rw_semaphore structure that includes the following fields: count Stores two 16-bit counters. The counter in the most significant word encodes in two's complement form the sum of the number of nonwaiting writers (either 0 or 1) and the number of waiting kernel control paths. The counter in the less significant word encodes the total number of nonwaiting readers and writers. wait_list Points to a list of waiting processes. Each element in this list is a rwsem_waiter structure, including a pointer to the descriptor of the sleeping process and a flag indicating whether the process wants the semaphore for reading or for writing. wait_lock A spin lock used to protect the wait queue list and the rw_semaphore structure itself. The init_rwsem( ) function initializes a rw_semaphore structure by setting the count field to 0, the wait_lock spin lock to unlocked, and wait_list to the empty list. The down_read( ) and down_write( ) functions acquire the read/write semaphore for reading and writing, respectively. Similarly, the up_read( ) and up_write( ) functions release a read/write semaphore previously acquired for reading and for writing. The implementation of these four functions is long, but easy to follow because it resembles the implementation of normal semaphores; therefore, we avoid describing them. 5.3.8 Completions Linux 2.4 also makes use of another synchronization primitive similar to semaphores: the completions. They have been introduced to solve a subtle race condition that occurs in multiprocessor systems when process A allocates a temporary semaphore variable, initializes it as closed MUTEX, passes its address to process B, and then invokes down( ) on it. Later on, process B running on a different CPU invokes up( ) on the same semaphore. However, the current implementation of up( ) and down( ) also allows them to execute concurrently on the same semaphore. Thus, process A can be woken up and destroy the temporary semaphore while process B is still executing the up( ) function. As a result, up( ) might attempt to access a data structure that no longer exists. Of course, it is possible to change the implementation of down( ) and up( ) to forbid concurrent executions on the same semaphore. However, this change would require additional instructions, which is a bad thing to do for functions that are so heavily used. The completion is a synchronization primitive that is specifically designed to solve this problem. The completion data structure includes a wait queue head and a flag: struct completion { unsigned int done; wait_queue_head_t wait; }; The function corresponding to up( ) is called complete( ). It receives as an argument the address of a completion data structure, sets the done field to 1, and invokes wake_up( ) to wake up the exclusive process sleeping in the wait wait queue. The function corresponding to down( ) is called wait_for_completion( ). It receives as an argument the address of a completion data structure and checks the value of the done flag. If it is set to 1, wait_for_completion( ) terminates because complete( ) has already been executed on another CPU. Otherwise, the function adds current to the tail of the wait queue as an exclusive process and puts current to sleep in the TASK_UNINTERRUPTIBLE state. Once woken up, the function removes current from the wait queue, sets done to 0, and terminates. The real difference between completions and semaphores is how the spin lock included in the wait queue is used. Both complete( ) and wait_for_completion( ) use this spin lock to ensure that they cannot execute concurrently, while up( ) and down( ) use it only to serialize accesses to the wait queue list. 5.3.9 Local Interrupt Disabling Interrupt disabling is one of the key mechanisms used to ensure that a sequence of kernel statements is treated as a critical section. It allows a kernel control path to continue executing even when hardware devices issue IRQ signals, thus providing an effective way to protect data structures that are also accessed by interrupt handlers. By itself, however, local interrupt disabling does not protect against concurrent accesses to data structures by interrupt handlers running on other CPUs, so in multiprocessor systems, local interrupt disabling is often coupled with spin locks (see the later section Section 5.4). Interrupts can be disabled on a CPU with the cli assembly language instruction, which is yielded by the _ _cli( ) macro. Interrupts can be enabled on a CPU by means of the sti assembly language instruction, which is yielded by the _ _sti( ) macro. Recent kernel versions also define the local_irq_disable( ) and local_irq_enable( ) macros, which are equivalent respectively to _ _cli( ) and _ _sti( ), but whose names are not architecture dependent and are also much easier to understand. When the kernel enters a critical section, it clears the IF flag of the eflags register to disable interrupts. But at the end of the critical section, often the kernel can't simply set the flag again. Interrupts can execute in nested fashion, so the kernel does not necessarily know what the IF flag was before the current control path executed. In these cases, the control path must save the old setting of the flag and restore that setting at the end. Saving and restoring the eflags content is achieved by means of the _ _save_flags and _ _restore_flags macros, respectively. Typically, these macros are used in the following way: _ _save_flags(old); _ _cli( ); [...] _ _restore_flags(old); The _ _save_flags macro copies the content of the eflags register into the old local variable; the IF flag is then cleared by _ _cli( ). At the end of the critical region, the macro _ _restore_flags restores the original content of eflags; therefore, interrupts are enabled only if they were enabled before this control path issued the _ _cli( ) macro. Recent kernel versions also define the local_irq_save( ) and local_irq_restore( ) macros, which are essentially equivalent to _ _save_flags( ) and _ _restore_flags( ), but whose names are easier to understand. 5.3.10 Global Interrupt Disabling Some critical kernel functions can execute on a CPU only if no interrupt handler or deferrable function is running on any other CPU. This synchronization requirement is satisfied by global interrupt disabling. A typical scenario consists of a driver that needs to reset the hardware device. Before fiddling with I/O ports, the driver performs global interrupt disabling, ensuring that no other driver will access the same ports. As we shall see in this section, global interrupt disabling significantly lowers the system concurrency level; it is deprecated because it can be replaced by more efficient synchronization techniques. Global interrupt disabling is performed by the cli( ) macro. On uniprocessor system, the macro just expands into _ _cli( ), disabling local interrupts. On multiprocessor systems, the macro waits until all interrupt handlers and all deferrable functions in the other CPUs terminate, and then acquires the global_irq_lock spin lock. The key activities required for multiprocessor systems occur inside the _ _global_cli( ) function, which is called by cli( ): _ _save_flags(flags); if (!(flags & 0x00000200)) /* testing IF flag */ { _ _cli( ); if (!local_irq_count[smp_processor_id( )]) get_irqlock(smp_processor_id( )); } First of all, _ _global_cli( ) checks the value of the IF flag of the eflags register because it refuses to "promote" the disabling of a local interrupt to a global one. Deadlock conditions can easily occur if this constraint is removed and global interrupts are disabled inside a critical region protected by a spin lock. For instance, consider a spin lock that is also accessed by interrupt handlers. Before acquiring the spin lock, the kernel must disable local interrupts, otherwise an interrupt handler could freeze waiting until the interrupted program released the spin lock. Now, suppose that a kernel control path disables local interrupts, acquires the spin lock, and then invokes cli( ). The latter macro waits until all interrupt handlers on the other CPUs terminate; however, an interrupt handler could be stuck waiting for the spin lock to be released. To avoid this kind of deadlock, _ _global_cli( ) refuses to run if local interrupts are already disabled before its invocation. If cli( ) is invoked with local interrupts enabled, _ _global_cli( ) disables them. If cli( ) is invoked inside an interrupt service routine (i.e., local_irq_count macro returns a value different than 0), _ _global_cli( ) returns without performing any further action.[6] Otherwise, _ _global_irq( ) invokes the get_irqlock( ) function, which acquires the global_irq_lock spin lock and waits for the termination of all interrupt handlers running on the other CPUs. Moreover, if cli( ) is not invoked by a deferrable function, get_irqlock( ) waits for the termination of all bottom halves running on the other CPUs. [6] This case should never occur because protection against concurrent execution of interrupt handlers should be based on spin locks rather than on global interrupt disabling. In short, an interrupt service routine should never execute the cli( ) macro. global_irq_lock differs from normal spin locks because invoking get_irqlock( ) does not freeze the CPU if it already owns the lock. In fact, the global_irq _holder variable contains the logical identifier of the CPU that is holding the lock; this value is checked by get_irqlock( ) before starting the tight loop of the spin lock. Once cli( ) returns, no other interrupt handler on other CPUs starts running until interrupts are re-enabled by invoking the sti( ) macro. On multiprocessor systems, sti( ) invokes the _ _global_sti( ) function: cpu = smp_processor_id( ); if (!local_irq_count[cpu]) release_irqlock(cpu); _ _sti( ); The release_irqlock( ) function releases the global_irq_lock spin lock. Notice that similar to cli( ), the sti( ) macro invoked inside an interrupt service routine is equivalent to _ _sti( ) because it doesn't release the spin lock. Linux also provides global versions of the _ _save_flags and _ _restore_flags macros, which are also called save_flags and restore_flags. They save and reload, respectively, information controlling the interrupt handling for the executing CPU. As illustrated in Figure 5-3, save_flags yields an integer value that depends on three conditions; restore_flags performs actions based on the value yielded by save_flags. Figure 5-3. Actions performed by save_ flags( ) and restore_ flags( ) Finally, the synchronize_irq( ) function is called when a kernel control path wishes to synchronize itself with all interrupt handlers: for (i = 0; i < smp_num_cpus; i++) if (local_irq_count(i)) { cli( ); sti( ); break; } By invoking cli( ), the function acquires the global_irq _lock spin lock and then waits until all executing interrupt handlers terminate; once this is done, it reenables interrupts. The synchronize_irq( ) function is usually called by device drivers when they want to make sure that all activities carried on by interrupt handlers are over. 5.3.11 Disabling Deferrable Functions In Section 4.7.1, we explained that deferrable functions can be executed at unpredictable times (essentially, on termination of hardware interrupt handlers). Therefore, data structures accessed by deferrable functions must be protected against race conditions. A trivial way to forbid deferrable functions execution on a CPU is to disable interrupts on that CPU. Since no interrupt handler can be activated, softirq actions cannot be started asynchronously. Globally disabling interrupts on all CPUs also disable deferrable functions on all CPUs. In fact, recall that the do_softirq( ) function refuses to execute the softirqs when the global_irq_lock spin lock is closed. When the cli( ) macro returns, the invoking kernel control path can assume that no deferrable function is in execution on any CPU, and that none are started until interrupts are globally re-enabled. As we shall see in the next section, however, the kernel sometimes needs to disable deferrable functions without disabling interrupts. Local deferrable functions can be disabled on each CPU by setting the _ _local_bh_count field of the irq_stat structure associated with the CPU to a nonzero value. Recall that the do_softirq( ) function never executes the softirqs if it finds a nonzero value in this field. Moreover, tasklets and bottom halves are implemented on top of softirqs, so writing a nonzero value in the field disables the execution of all deferrable functions on a given CPU, not just softirqs. The local_bh_disable macro increments the _ _local_bh_count field by 1, while the local_bh_enable macro decrements it. The kernel can thus use several nested invocations of local_bh_disable; deferrable functions will be enabled again only by the local_bh_enable macro matching the first local_bh_disable invocation. I l@ve RuBoard I l@ve RuBoard 5.4 Synchronizing Accesses to Kernel Data Structures A shared data structure can be protected against race conditions by using some of the synchronization primitives shown in the previous section. Of course, system performances may vary considerably, depending on the kind of synchronization primitive selected. Usually, the following rule of thumb is adopted by kernel developers: always keep the concurrency level as high as possible in the system. In turn, the concurrency level in the system depends on two main factors: 1. The number of I/O devices that operate concurrently 2. The number of CPUs that do productive work To maximize I/O throughput, interrupts should be disabled for very short periods of time. As described in Section 4.2.1, when interrupts are disabled, IRQs issued by I/O devices are temporarily ignored by the PIC and no new activity can start on such devices. To use CPUs efficiently, synchronization primitives based on spin locks should be avoided whenever possible. When a CPU is executing a tight instruction loop waiting for the spin lock to open, it is wasting precious machine cycles. Let's illustrate a couple of cases in which synchronization can be achieved while still maintaining a high concurrency level. ● A shared data structure consisting of a single integer value can be updated by declaring it as an atomic_t type and by using atomic operations. An atomic operation is faster than spin locks and interrupt disabling, and it slows down only kernel control paths that concurrently access the data structure. ● Inserting an element into a shared linked list is never atomic since it consists of at least two pointer assignments. Nevertheless, the kernel can sometimes perform this insertion operation without using locks or disabling interrupts. As an example of why this works, we'll consider the case where a system call service routine (see Section 9.2) inserts new elements in a simply linked list, while an interrupt handler or deferrable function asynchronously looks up the list. In the C language, insertion is implemented by means of the following pointer assignments: new->next = list_element->next; list_element->next = new; In assembly language, insertion reduces to two consecutive atomic instructions. The first instruction sets up the next pointer of the new element, but it does not modify the list. Thus, if the interrupt handler sees the list between the execution of the first and second instructions, it sees the list without the new element. If the handler sees the list after the execution of the second instruction, it sees the list with the new element. The important point is that in either case, the list is consistent and in an uncorrupted state. However, this integrity is assured only if the interrupt handler does not modify the list. If it does, the next pointer that was just set within the new element might become invalid. However, developers must ensure that the order of the two assignment operations cannot be subverted by the compiler or the CPU's control unit; otherwise, if the system call service routine is interrupted by the interrupt handler between the two assignments, the handler finds a corrupted list. Therefore, a write memory barrier primitive is required: new->next = list_element->next; wmb( ); list_element->next = new; 5.4.1 Choosing Among Spin Locks, Semaphores, and Interrupt Disabling Unfortunately, access patterns to most kernel data structures are a lot more complex than the simple examples just shown, and kernel developers are forced to use semaphores, spin locks, interrupts, and softirq disabling. Generally speaking, choosing the synchronization primitives depends on what kinds of kernel control paths access the data structure, as shown in Table 5-6. Table 5-6. Protection required by data structures accessed by kernel control paths Kernel control paths accessing the data structure UP protection MP further protection Exceptions Semaphore None Interrupts Local interrupt disabling Spin lock Deferrable functions None None or spin lock (see Table 5-8) Exceptions + Interrupts Local interrupt disabling Spin lock Exceptions + Deferrable functions Local softirq disabling Spin lock Interrupts + Deferrable functions Local interrupt disabling Spin lock Exceptions + Interrupts + Deferrable functions Local interrupt disabling Spin lock Notice that global interrupt disabling does not appear in the table. Delaying interrupts on all CPUs significantly lowers the system concurrency level, so global interrupt disabling is usually deprecated and should be replaced by other synchronization techniques. As a matter of fact, this synchronization technique is still available in Linux 2.4 to support old device drivers; it has been removed from the Linux 2.5 current development version. 5.4.1.1 Protecting a data structure accessed by exceptions When a data structure is accessed only by exception handlers, race conditions are usually easy to understand and prevent. The most common exceptions that give rise to synchronization problems are the system call service routines (see Section 9.2) in which the CPU operates in Kernel Mode to offer a service to a User Mode program. Thus, a data structure accessed only by an exception usually represents a resource that can be assigned to one or more processes. Race conditions are avoided through semaphores because these primitives allow the process to sleep until the resource becomes available. Notice that semaphores work equally well both in uniprocessor and multiprocessor systems. 5.4.1.2 Protecting a data structure accessed by interrupts Suppose that a data structure is accessed by only the "top half" of an interrupt handler. We learned in Section 4.6 that each interrupt handler is serialized with respect to itself — that is, it cannot execute more than once concurrently. Thus, accessing the data structure does not require any synchronization primitive. Things are different, however, if the data structure is accessed by several interrupt handlers. A handler may interrupt another handler, and different interrupt handlers may run concurrently in multiprocessor systems. Without synchronization, the shared data structure might easily become corrupted. In uniprocessor systems, race conditions must be avoided by disabling interrupts in all critical regions of the interrupt handler. Nothing less will do because no other synchronization primitives accomplish the job. A semaphore can block the process, so it cannot be used in an interrupt handler. A spin lock, on the other hand, can freeze the system: if the handler accessing the data structure is interrupted, it cannot release the lock; therefore, the new interrupt handler keeps waiting on the tight loop of the spin lock. Multiprocessor systems, as usual, are even more demanding. Race conditions cannot be avoided by simply disabling local interrupts. In fact, even if interrupts are disabled on a CPU, interrupt handlers can still be executed on the other CPUs. The most convenient method to prevent the race conditions is to disable local interrupts (so that other interrupt handlers running on the same CPU won't interfere) and to acquire a spin lock or a read/write spin lock that protects the data structure. Notice that these additional spin locks cannot freeze the system because even if an interrupt handler finds the lock closed, eventually the interrupt handler on the other CPU that owns the lock will release it. The Linux kernel uses several macros that couple local interrupts enabling/disabling with spin lock handling. Table 5-7 describes all of them. In uniprocessor systems, these macros just enable or disable local interrupts because the spin lock handling macros does nothing. Table 5-7. Interrupt-aware spin lock macros Function Description spin_lock_irq(l) local_irq_disable( ); spin_lock(l) spin_unlock_irq(l) spin_unlock(l); local_irq_enable( ) spin_lock_irqsave(l,f) local_irq_save(f); spin_lock(l) spin_unlock_irqrestore(l,f) spin_unlock(l); local_irq_restore(f) read_lock_irq(l) local_irq_disable( ); read_lock(l) read_unlock_irq(l) read_unlock(l); local_irq_enable( ) write_lock_irq(l) local_irq_disable( ); write_lock(l) write_unlock_irq(l) write_unlock(l); local_irq_enable( ) read_lock_irqsave(l,f) local_irq_save(f); read_lock(l) read_unlock_irqrestore(l,f) read_unlock(l); local_irq_restore(f) write_lock_irqsave(l,f) local_irq_save(f); write_lock(l) write_unlock_irqrestore(l,f) write_unlock(l); local_irq_restore(f) 5.4.1.3 Protecting a data structure accessed by deferrable functions What kind of protection is required for a data structure accessed only by deferrable functions? Well, it mostly depends on the kind of deferrable function. In Section 4.7, we explained that softirqs, tasklets, and bottom halves essentially differ in their degree of concurrency. First of all, no race condition may exist in uniprocessor systems. This is because execution of deferrable functions is always serialized on a CPU — that is, a deferrable function cannot be interrupted by another deferrable function. Therefore, no synchronization primitive is ever required. Conversely, in multiprocessor systems, race conditions do exist because several deferrable functions may run concurrently. Table 5-8 lists all possible cases. Table 5-8. Protection required by data structures accessed by deferrable functions in SMP Deferrable functions accessing the data structure Protection Softirqs Spin lock One tasklet None Many tasklets Spin lock Bottom halves None A data structure accessed by a softirq must always be protected, usually by means of a spin lock, because the same softirq may run concurrently on two or more CPUs. Conversely, a data structure accessed by just one kind of tasklet need not be protected, because tasklets of the same kind cannot run concurrently. However, if the data structure is accessed by several kinds of tasklets, then it must be protected. Finally, a data structure accessed only by bottom halves need not be protected because bottom halves never run concurrently. Notice that it is also possible to prevent the race conditions by globally disabling the deferrable functions by means of the cli( ) macro. However, this should be avoided because the macro also disables the execution of interrupt handlers on all CPUs of the system. 5.4.1.4 Protecting a data structure accessed by exceptions and interrupts Let's consider now a data structure that is accessed both by exceptions (for instance, system call service routines) and interrupt handlers. On uniprocessor systems, race condition prevention is quite simple because interrupt handlers are not re-entrant and cannot be interrupted by exceptions. So long as the kernel accesses the data structure with local interrupts disabled, the kernel cannot be interrupted when accessing the data structure. However, if the data structure is accessed by just one kind of interrupt handler, the interrupt handler can freely access the data structure without disabling local interrupts. On multiprocessor systems, we have to take care of concurrent executions of exceptions and interrupts on other CPUs. Local interrupt disabling must be coupled with a spin lock, which forces the concurrent kernel control paths to wait until the handler accessing the data structure finishes its work. Sometimes it might be preferable to replace the spin lock with a semaphore. Since interrupt handlers cannot be suspended, they must acquire the semaphore using a tight loop and the down_trylock( ) function; for them, the semaphore acts essentially as a spin lock. System call service routines, on the other hand, may suspend the calling processes when the semaphore is busy. For most system calls, this is the expected behavior; it is preferable because it increases the degree of concurrency of the system. 5.4.1.5 Protecting a data structure accessed by exceptions and deferrable functions A data structure accessed both by exception handlers and deferrable functions can be treated like a data structure accessed by exception and interrupt handlers. In fact, deferrable functions are essentially activated by interrupt occurrences, and no exception can be raised while a deferrable function is running. Coupling local interrupt disabling with a spin lock is therefore sufficient. Actually, this is much more than sufficient: the exception handler can simply disable deferrable functions instead of local interrupts by using the local_bh_disable( ) macro (see Section 4.7.1). Disabling only the deferrable functions is preferable to disabling interrupts because interrupts continue to be serviced on the CPU. Execution of deferrable functions on each CPU is serialized, so no race condition exists. As usual, in multiprocessor systems, spin locks are required to ensure that the data structure is accessed at any time by just one kernel control path.[7] [7] The spin lock is required even when the data structure is accessed only by exception handlers and bottom halves (see Section 4.7). The kernel ensures that two bottom halves never run concurrently, but this is not enough to prevent race conditions. 5.4.1.6 Protecting a data structure accessed by interrupts and deferrable functions This case is similar to that of a data structure accessed by interrupt and exception handlers. An interrupt might be raised while a deferrable function is running, but no deferrable function can stop an interrupt handler. Therefore, race conditions must be avoided by disabling local interrupts. However, an interrupt handler can freely touch the data structure accessed by the deferrable function without disabling interrupts, provided that no other interrupt handler accesses that data structure. Again, in multiprocessor systems, a spin lock is always required to forbid concurrent accesses to the data structure on several CPUs. 5.4.1.7 Protecting a data structure accessed by exceptions, interrupts, and deferrable functions Similarly to previous cases, disabling local interrupts and acquiring a spin lock is almost always necessary to avoid race conditions. Notice that there is no need to explicitly disable deferrable functions because they are essentially activated when terminating the execution of interrupt handlers; disabling local interrupts is therefore sufficient. I l@ve RuBoard I l@ve RuBoard 5.5 Examples of Race Condition Prevention Kernel developers are expected to identify and solve the synchronization problems raised interleaving by kernel control paths. However, avoiding race conditions is a hard task because it requires a clear understanding of how the various components of the kernel interact. To give a feeling of what's really inside the kernel code, let's mention a few typical usages of the synchronization primitives defined in this chapter. 5.5.1 Reference Counters Reference counters are widely used inside the kernel to avoid race conditions due to the concurrent allocation and releasing of a resource. A reference counter is just an atomic_t counter associated with a specific resource like a memory page, a module, or a file. The counter is atomically incremented when a kernel control path starts using the resource, and it is decremented when a kernel control path finishes using the resource. When the reference counter becomes zero, the resource is not being used, and it can be released if necessary. 5.5.2 The Global Kernel Lock In earlier Linux kernel versions, a global kernel lock (also known as big kernel lock, or BKL) was widely used. In Version 2.0, this lock was a relatively crude spin lock, ensuring that only one processor at a time could run in Kernel Mode. The 2.2 kernel was considerably more flexible and no longer relied on a single spin lock; rather, a large number of kernel data structures were protected by specialized spin locks. The global kernel lock, on other hand, was still present because splitting a big lock into several smaller locks is not trivial — both deadlocks and race conditions must be carefully avoided. Several unrelated parts of the kernel code were still serialized by the global kernel lock. Linux kernel Version 2.4 reduces still further the role of the global kernel lock. In the current stable version, the global kernel lock is mostly used to serialize accesses to the Virtual File System and avoid race conditions when loading and unloading kernel modules. The main progress with respect to the earlier stable version is that the networking transfers and file accessing (like reading or writing into a regular file) are no longer serialized by the global kernel lock. The global kernel lock is a spin lock named kernel_flag. Every process descriptor includes a lock_depth field, which allows the same process to acquire the global kernel lock several times. Therefore, two consecutive requests for it will not hang the processor (as for normal spin locks). If the process does not want the lock, the field has the value -1. If the process wants it, the field value plus 1 specifies how many times the lock has been requested. The lock_depth field is crucial for interrupt handlers, exception handlers, and bottom halves. Without it, any asynchronous function that tries to get the global kernel lock could generate a deadlock if the current process already owns the lock. The lock_kernel( ) and unlock_kernel( ) functions are used to get and release the global kernel lock. The former function is equivalent to: if (++current->lock_depth == 0) spin_lock(&kernel_flag); while the latter is equivalent to: if (--current->lock_depth < 0) spin_unlock(&kernel_flag); Notice that the if statements of the lock_kernel( ) and unlock_kernel( ) functions need not be executed atomically because lock_depth is not a global variable — each CPU addresses a field of its own current process descriptor. Local interrupts inside the if statements do not induce race conditions either. Even if the new kernel control path invokes lock_kernel( ), it must release the global kernel lock before terminating. 5.5.3 Memory Descriptor Read/Write Semaphore Each memory descriptor of type mm_struct includes its own semaphore in the mmap_sem field (see Section 8.2). The semaphore protects the descriptor against race conditions that could arise because a memory descriptor can be shared among several lightweight processes. For instance, let's suppose that the kernel must create or extend a memory region for some process; to do this, it invokes the do_mmap( ) function, which allocates a new vm_area_struct data structure. In doing so, the current process could be suspended if no free memory is available, and another process sharing the same memory descriptor could run. Without the semaphore, any operation of the second process that requires access to the memory descriptor (for instance, a Page Fault due to a Copy on Write) could lead to severe data corruption. The semaphore is implemented as a read/write semaphore because some kernel functions, such as the Page Fault exception handler (see Section 8.4), need only to scan the memory descriptors. 5.5.4 Slab Cache List Semaphore The list of slab cache descriptors (see Section 7.2.2) is protected by the cache_chain_sem semaphore, which grants an exclusive right to access and modify the list. A race condition is possible when kmem_cache_create( ) adds a new element in the list, while kmem_cache_shrink( ) and kmem_cache_reap( ) sequentially scan the list. However, these functions are never invoked while handling an interrupt, and they can never block while accessing the list. Since the kernel is nonpreemptive, these functions cannot overlap on a uniprocessor system. However, this semaphore plays an active role in multiprocessor systems. 5.5.5 Inode Semaphore As we shall see in Chapter 12, Linux stores the information on a disk file in a memory object called an inode. The corresponding data structure includes its own semaphore in the i_sem field. A huge number of race conditions can occur during filesystem handling. Indeed, each file on disk is a resource held in common for all users, since all processes may (potentially) access the file content, change its name or location, destroy or duplicate it, and so on. For example, let's suppose that a process lists the files contained in some directory. Each disk operation is potentially blocking, and therefore even in uniprocessor systems, other processes could access the same directory and modify its content while the first process is in the middle of the listing operation. Or, again, two different processes could modify the same directory at the same time. All these race conditions are avoided by protecting the directory file with the inode semaphore. Whenever a program uses two or more semaphores, the potential for deadlock is present because two different paths could end up waiting for each other to release a semaphore. Generally speaking, Linux has few problems with deadlocks on semaphore requests, since each kernel control path usually needs to acquire just one semaphore at a time. However, in a couple of cases, the kernel must get two semaphore locks. Inode semaphores are prone to this scenario; for instance, this occurs in the service routines of the rmdir( ) and the rename( ) system calls (notice that in both cases two different inodes are involved in the operation, so both semaphores must be taken). To avoid such deadlocks, semaphore requests are performed in address order: the semaphore request whose semaphore data structure is located at the lowest address is issued first. I l@ve RuBoard I l@ve RuBoard Chapter 6. Timing Measurements Countless computerized activities are driven by timing measurements, often behind the user's back. For instance, if the screen is automatically switched off after you have stopped using the computer's console, it is due to a timer that allows the kernel to keep track of how much time has elapsed since you pushed a key or moved the mouse. If you receive a warning from the system asking you to remove a set of unused files, it is the outcome of a program that identifies all user files that have not been accessed for a long time. To do these things, programs must be able to retrieve a timestamp identifying its last access time from each file. Such a timestamp must be automatically written by the kernel. More significantly, timing drives process switches along with even more visible kernel activities like checking for time-outs. We can distinguish two main kinds of timing measurement that must be performed by the Linux kernel: ● Keeping the current time and date so they can be returned to user programs through the time( ), ftime( ), and gettimeofday( ) system calls (see Section 6.7.1 later in this chapter) and used by the kernel itself as timestamps for files and network packets ● Maintaining timers — mechanisms that are able to notify the kernel (see the later section Section 6.6) or a user program (see the later section Section 6.7.3) that a certain interval of time has elapsed Timing measurements are performed by several hardware circuits based on fixed-frequency oscillators and counters. This chapter consists of four different parts. The first two sections describe the hardware devices that underlie timing and give an overall picture of Linux timekeeping architecture. The following sections describe the main time-related duties of the kernel: implementing CPU time sharing, updating system time and resource usage statistics, and maintaining software timers. The last section discusses the system calls related to timing measurements and the corresponding service routines. I l@ve RuBoard I l@ve RuBoard 6.1 Hardware Clocks On the 80 x 86 architecture, the kernel must explicitly interact with four kinds of clocks: the Real Time Clock, the Time Stamp Counter, the Programmable Interval Timer, and the timer of the local APICs in SMP systems. The first two hardware devices allow the kernel to keep track of the current time of day. The PIC device and the timers of the local APICs are programmed by the kernel so that they issue interrupts at a fixed, predefined frequency; such periodic interrupts are crucial for implementing the timers used by the kernel and the user programs. 6.1.1 Real Time Clock All PCs include a clock called Real Time Clock (RTC ), which is independent of the CPU and all other chips. The RTC continues to tick even when the PC is switched off, since it is energized by a small battery or accumulator. The CMOS RAM and RTC are integrated in a single chip (the Motorola 146818 or an equivalent). The RTC is capable of issuing periodic interrupts on IRQ 8 at frequencies ranging between 2 Hz and 8,192 Hz. It can also be programmed to activate the IRQ 8 line when the RTC reaches a specific value, thus working as an alarm clock. Linux uses the RTC only to derive the time and date; however, it allows processes to program the RTC by acting on the /dev/rtc device file (see Chapter 13). The kernel accesses the RTC through the 0x70 and 0x71 I/O ports. The system administrator can set up the clock by executing the clock Unix system program that acts directly on these two I/O ports. 6.1.2 Time Stamp Counter All 80 x 86 microprocessors include a CLK input pin, which receives the clock signal of an external oscillator. Starting with the Pentium, many recent 80 x 86 microprocessors include a 64-bit Time Stamp Counter (TSC ) register that can be read by means of the rdtsc assembly language instruction. This register is a counter that is incremented at each clock signal — if, for instance, the clock ticks at 400 MHz, the Time Stamp Counter is incremented once every 2.5 nanoseconds. Linux takes advantage of this register to get much more accurate time measurements than those delivered by the Programmable Interval Timer. To do this, Linux must determine the clock signal frequency while initializing the system. In fact, since this frequency is not declared when compiling the kernel, the same kernel image may run on CPUs whose clocks may tick at any frequency. The task of figuring out the actual frequency of a CPU is accomplished during the system's boot. The calibrate_tsc( ) function computes the frequency by counting the number of clock signals that occur in a relatively long time interval, namely 50.00077 milliseconds. This time constant is produced by properly setting up one of the channels of the Programmable Interval Timer (see the next section). The long execution time of calibrate_tsc( ) does not create problems, since the function is invoked only during system initialization.[1] [1] To avoid losing significant digits in the integer divisions, calibrate_tsc( ) returns the duration, in microseconds, of a clock tick multiplied by 232. 6.1.3 Programmable Interval Timer Besides the Real Time Clock and the Time Stamp Counter, IBM-compatible PCs include another type of time-measuring device called Programmable Interval Timer (PIT ). The role of a PIT is similar to the alarm clock of a microwave oven: it makes the user aware that the cooking time interval has elapsed. Instead of ringing a bell, this device issues a special interrupt called timer interrupt, which notifies the kernel that one more time interval has elapsed.[2] Another difference from the alarm clock is that the PIT goes on issuing interrupts forever at some fixed frequency established by the kernel. Each IBM-compatible PC includes at least one PIT, which is usually implemented by a 8254 CMOS chip using the 0x40-0x43 I/O ports. [2] The PIT is also used to drive an audio amplifier connected to the computer's internal speaker. As we shall see in detail in the next paragraphs, Linux programs the PIT to issue timer interrupts on the IRQ0 at a (roughly) 100-Hz frequency — that is, once every 10 milliseconds. This time interval is called a tick, and its length in microseconds is stored in the tick variable. The ticks beat time for all activities in the system; in some sense, they are like the ticks sounded by a metronome while a musician is rehearsing. Generally speaking, shorter ticks result in higher resolution timers, which help with smoother multimedia playback and faster response time when performing synchronous I/O multiplexing (poll( ) and select( ) system calls). This is a trade-off however: shorter ticks require the CPU to spend a larger fraction of its time in Kernel Mode — that is, a smaller fraction of time in User Mode. As a consequence, user programs run slower. Therefore, only very powerful machines can adopt very short ticks and afford the consequent overhead. Currently, most Hewlett-Packard's Alpha and Intel's IA-64 ports of the Linux kernel issue 1,024 timer interrupts per second, corresponding to a tick of roughly 1 millisecond. The Rawhide Alpha station adopts the highest tick frequency and issues 1,200 timer interrupts per second. A few macros in the Linux code yield some constants that determine the frequency of timer interrupts. These are discussed in the following list. ● HZ yields the number of timer interrupts per second — that is, their frequency. This value is set to 100 for IBM PCs and most other hardware platforms. ● CLOCK_TICK_RATE yields the value 1,193,180, which is the 8254 chip's internal oscillator frequency. ● LATCH yields the ratio between CLOCK_TICK_RATE and HZ. It is used to program the PIT. The first PIT is initialized by init_IRQ( ) as follows: outb_p(0x34,0x43); outb_p(LATCH & 0xff , 0x40); outb(LATCH >> 8 , 0x40); The outb( ) C function is equivalent to the outb assembly language instruction: it copies the first operand into the I/O port specified as the second operand. The outb_p( ) function is similar to outb( ), except that it introduces a pause by executing a no-op instruction. The first outb_ p( ) invocation is a command to the PIT to issue interrupts at a new rate. The next two outb_ p( ) and outb( ) invocations supply the new interrupt rate to the device. The 16-bit LATCH constant is sent to the 8-bit 0x40 I/O port of the device as two consecutive bytes. As a result, the PIT issues timer interrupts at a (roughly) 100-Hz frequency (that is, once every 10 ms). 6.1.4 CPU Local Timers The local APIC present in recent Intel processors (see Section 4.2) provides yet another time- measuring device: the CPU local timer. The CPU local timer is a device that can issue one-shot or periodic interrupts, which is similar to the Programmable Interval Timer just described. There are, however, a few differences: ● The APIC's timer counter is 32-bits long, while the PIT's timer counter is 16-bits long; therefore, the local timer can be programmed to issue interrupts at very low frequencies (the counter stores the number of ticks that must elapse before the interrupt is issued). ● The local APIC timer sends an interrupt only to its processor, while the PIT raises a global interrupt, which may be handled by any CPU in the system. ● The APIC's timer is based on the bus clock signal (or the APIC bus signal, in older machines). It can be programmed in such a way to decrement the timer counter every 1, 2, 4, 8, 16, 32, 64, or 128 bus clock signals. Conversely, the PIT has its own internal clock oscillator. Now that we understand what the hardware timers are, we may discuss how the Linux kernel exploits them to conduct all activities of the system. I l@ve RuBoard I l@ve RuBoard 6.2 The Linux Timekeeping Architecture Linux must carry on several time-related activities. For instance, the kernel periodically: ● Updates the time elapsed since system startup. ● Updates the time and date. ● Determines, for every CPU, how long the current process has been running, and preempts it if it has exceeded the time allocated to it. The allocation of time slots (also called quanta) is discussed in Chapter 11. ● Updates resource usage statistics. ● Checks whether the interval of time associated with each software timer (see the later section Section 6.6) has elapsed. Linux's timekeeping architecture is the set of kernel data structures and functions related to the flow of time. Actually, Intel-based multiprocessor machines have a timekeeping architecture that is slightly different from the timekeeping architecture of uniprocessor machines: ● In a uniprocessor system, all time-keeping activities are triggered by interrupts raised by the Programmable Interval Timer. ● In a multiprocessor system, all general activities (like handling of software timers) are triggered by the interrupts raised by the PIT, while CPU-specific activities (like monitoring the execution time of the currently running process) are triggered by the interrupts raised by the local APIC timers. Unfortunately, the distinction between the two cases is somewhat blurred. For instance, some early SMP systems based on Intel 80486 processors didn't have local APICs. Even nowadays, there are SMP motherboards so buggy that local timer interrupts are not usable at all. In these cases, the SMP kernel must resort to the UP timekeeping architecture. On the other hand, recent uniprocessor systems have a local APIC and an I/O APIC, so the kernel may use the SMP timekeeping architecture. Another significant case holds when a SMP-enabled kernel is running on a uniprocessor machine. However, to simplify our description, we won't discuss these hybrid cases and will stick to the two "pure" timekeeping architectures. Linux's timekeeping architecture depends also on the availability of the Time Stamp Counter (TSC). The kernel uses two basic timekeeping functions: one to keep the current time up to date and another to count the number of microseconds that have elapsed within the current second. There are two different ways to get the last value. One method is more precise and is available if the CPU has a Time Stamp Counter; a less-precise method is used in the opposite case (see the later section Section 6.7.1). 6.2.1 Timekeeping Architecture in Uniprocessor Systems In a uniprocessor system, all time-related activities are triggered by the interrupts raised by the Programmable Interval Timer on IRQ line 0. As usual, in Linux, some of these activities are executed as soon as possible after the interrupt is raised (in the "top half" of the interrupt handler), while the remaining activities are delayed (in the "bottom half" of the interrupt handler). 6.2.1.1 PIT's interrupt service routine The time_init( ) function sets up the interrupt gate corresponding to IRQ 0 during kernel setup. Once this is done, the handler field of IRQ 0's irqaction descriptor contains the address of the timer_interrupt( ) function. This function starts running with the interrupts disabled, since the status field of IRQ 0's main descriptor has the SA_INTERRUPT flag set. It performs the following steps: 1. If the CPU has a TSC register, it performs the following substeps: a. Executes an rdtsc assembly language instruction to store the 32 least- significant bits of the TSC register in the last_tsc_low variable. b. Reads the state of the 8254 chip device internal oscillator and computes the delay between the timer interrupt occurrence and the execution of the interrupt service routine.[3] [3] The 8254 oscillator drives a counter that is continuously decremented. When the counter becomes 0, the chip raises an IRQ 0. Thus, reading the counter indicates how much time has elapsed since the interrupt occurred. 2. Stores that delay (in microseconds) in the delay_at_last_interrupt variable; as we shall see in Section 6.7.1, this variable is used to provide the correct time to user processes. ● It invokes do_timer_interrupt( ). do_timer_interrupt( ), which may be considered the PIT's interrupt service routine common to all 80 x 86 models, essentially executes the following operations: 1. It invokes the do_timer( ) function, which is fully explained shortly. 2. If the timer interrupt occurred in Kernel Mode, it invokes the x86_do_profile( ) function (see Section 6.5.3 later in this chapter). 3. If an adjtimex( ) system call is issued, it invokes the set_rtc_mmss( ) function once every 660 seconds (every 11 minutes) to adjust the Real Time Clock. This feature helps systems on a network synchronize their clocks (see the later section Section 6.7.2). The do_timer( ) function, which runs with the interrupts disabled, must be executed as quickly as possible. For this reason, it simply updates one fundamental value—the time elapsed from system startup—and checks whether the running processes have exhausted its time quantum while delegating all remaining activities to the TIMER_BH bottom half. The function is equivalent to: void do_timer(struct pt_regs * regs) { jiffies++; update_process_times(user_mode(regs)); /* UP only */ mark_bh(TIMER_BH); if (TQ_ACTIVE(tq_timer)) mark_bh(TQUEUE_BH); } The jiffies global variable stores the number of elapsed ticks since the system was started. It is set to 0 during kernel initialization and incremented by 1 when a timer interrupt occurs — that is, on every tick. Since jiffies is a 32-bit unsigned integer, it returns to 0 about 497 days after the system has been booted. However, the kernel is smart enough to handle the overflow without getting confused. The update_process_times( ) function essentially checks how long the current process has been running; it is described in Section 6.3 later in this chapter. Finally do_timer( ) activates the TIMER_BH bottom half; if the tq_timer task queue is not empty (see Section 4.7), the function also activates the TQUEUE_BH bottom half. 6.2.1.2 The TIMER_BH bottom half Each invocation of the "top half" PIT's timer interrupt handler marks the TIMER_BH bottom half as active. As soon as the kernel leaves interrupt mode, the timer_bh( ) function, which is associated with TIMER_BH, starts: void timer_bh(void) { update_times( ); run_timer_list( ); } The update_times( ) function updates the system date and time and computes the current system load; these activities are discussed later in Section 6.4 and Section 6.5. The run_timer_list( ) function takes care of software timers handling; it is discussed in the later section Section 6.6. 6.2.2 Timekeeping Architecture in Multiprocessor Systems In multiprocessor systems, timer interrupts raised by the Programmable Interval Timer still play an important role. Indeed, the corresponding interrupt handler takes care of activities not related to a specific CPU, such as the handling of software timers and keeping the system time up to date. As in the uniprocessor case, the most urgent activities are performed by the "top half" of the interrupt handler (see Section 6.2.1.1 earlier in this chapter), while the remaining activities are delayed until the execution of the TIMER_BH bottom half (see the earlier section Section 6.2.1.2). However, the SMP version of the PIT's interrupt service routine differs from the UP version in a few points: ● The timer_interrupt( ) function acquires the xtime_lock read/write spin lock for writing. Although local interrupts are disabled, the kernel must protect the xtime, last_tsc_low, and delay_at_last_interrupt global variables from concurrent read and write accesses performed by other CPUs (see Section 6.4 later in this chapter). ● The do_timer_interrupt( ) function does not invoke the x86_do_profile( ) function because this function performs actions related to a specific CPU. ● The do_timer( ) function does not invoke update_process_times( ) because this function also performs actions related to a specific CPU. There are two timekeeping activities related to every specific CPU in the system: ● Monitoring how much time the current process has been running on the CPU ● Updating the resource usage statistics of the CPU To simplify the overall timekeeping architecture, in Linux 2.4, every CPU takes care of these activities in the handler of the local timer interrupt raised by the APIC device embedded in the CPU. In this way, the number of accessed spin locks is minimized, since every CPU tends to access only its own "private" data structures. 6.2.2.1 Initialization of the timekeeping architecture During kernel initialization, each APIC has to be told how often to generate a local time interrupt. The setup_APIC_clocks( ) function programs the local APICs of all CPUS to generate interrupts as follows: void setup_APIC_clocks (void) { _ _cli( ); calibration_result = calibrate_APIC_clock( ); setup_APIC_timer((void *)calibration_result); _ _sti( ); smp_call_function(setup_APIC_timer, (void *)calibration_result, 1, 1); } The calibrate_APIC_clock( ) function computes how many local timer interrupts are generated by the local APIC of the booting CPU during a tick (10 ms). This exact value is then used to program the local APICs in such a way to generate one local timer interrupt every tick. This is done by the setup_APIC_timer( ) function, which is invoked directly on the booting CPU, and through the CALL_FUNCTION_VECTOR Interprocessor Interrupts (IPI) on the other CPUs (see Section 4.6.2). All local APIC timers are synchronized because they are based on the common bus clock signal. This means that the value computed by calibrate_APIC_clock( ) for the booting CPU is good also for the other CPUs in the system. However, we don't really want to have all local timer interrupts generated at exactly the same time because this could induce a substantial performance penalty due to waits on spin locks. For the same reason, a local timer interrupt handler should not run on a CPU when a PIT's timer interrupt handler is being executed on another CPU. Therefore, the setup_APIC_timer( ) function spreads the local timer interrupts inside the tick interval. Figure 6-1 shows an example. In a multiprocessor systems with four CPUs, the beginning of the tick is marked by the PIT's timer interrupt. Two milliseconds after the PIT's timer interrupt, the local APIC of CPU 0 raises its local timer interrupt; two milliseconds later, it is the turn of the local APIC of CPU 1, and so on. Two milliseconds after the local timer interrupt of CPU 3, the PIT raises another timer interrupt on IRQ 0 line and starts a new tick. Figure 6-1. Spreading local timer interrupts inside a tick setup_APIC_timer( ) programs the local APIC in such a way to raise timer interrupts that have vector LOCAL_TIMER_VECTOR (usually, 0xef); moreover, the init_IRQ( ) function associates LOCAL_TIMER_VECTOR to the low-level interrupt handler apic_timer_interrupt( ). 6.2.2.2 The local timer interrupt handler The apic_timer_interrupt( ) assembly language function is equivalent to the following code: apic_timer_interrupt: pushl $LOCAL_TIMER_VECTOR-256 SAVE_ALL movl %esp,%eax pushl %eax call smp_apic_timer_interrupt addl $4,%esp jmp ret_from_intr As you can see, the low-level handler is very similar to the other low-level interrupt handlers already described in Chapter 4. The high-level interrupt handler called smp_apic_timer_interrupt( ) executes the following steps: 1. Gets the CPU logical number (say n) 2. Increments the nth entry of the apic_timer_irqs array by 1 (see Section 6.5.4 later in this chapter) 3. Acknowledges the interrupt on the local APIC 4. Calls the irq_enter( ) function to increment the nth entry of the local_irq_count array and to honor the global_irq_lock spin lock (see Chapter 5) 5. Invokes the smp_local_timer_interrupt( ) function 6. Calls the irq_exit( ) function to decrement the nth entry of the local_irq_count array 7. Invokes do_softirq( ) if some softirqs are pending (see Section 4.7.1) The smp_local_timer_interrupt( ) function executes the per-CPU timekeeping activities. Actually, it performs the following steps: 1. Invokes the x86_do_profile( ) function if the timer interrupt occurred in Kernel Mode (see Section 6.5.3 later in this chapter) 2. Invokes the update_process_times( ) function to check how long the current process has been running (see Section 6.6 later in this chapter)[4] [4] The system administrator can change the sample frequency of the kernel code profiler. To do this, the kernel changes the frequency at which local timer interrupts are generated. However, the smp_local_timer_interrupt( ) function keeps invoking the update_process_times( ) function exactly once every tick. Unfortunately, changing the frequency of a local timer interrupt destroys the elegant spreading of the local timer interrupts inside a tick interval. I l@ve RuBoard I l@ve RuBoard 6.3 CPU's Time Sharing Timer interrupts are essential for time-sharing the CPU among runnable processes (that is, those in the TASK_RUNNING state). As we shall see in Chapter 11, each process is usually allowed a quantum of time of limited duration: if the process is not terminated when its quantum expires, the schedule( ) function selects the new process to run. The counter field of the process descriptor specifies how many ticks of CPU time are left to the process. The quantum is always a multiple of a tick — a multiple of about 10 ms. The value of counter is updated at every tick by update_ process_times( ), which is invoked by either the PIT's timer interrupt handler on uniprocessor systems or the local timer interrupt handler in multiprocessor systems. The code is equivalent to the following: if (current->pid) { --current->counter; if (current->counter <= 0) { current->counter = 0; current->need_resched = 1; } } The snippet of code starts by making sure the kernel is not handling a process with PID 0 — the swapper process associated with the executing CPU. It must not be time-shared because it is the process that runs on the CPU when no other TASK_RUNNING processes exist (see Section 3.2.2). When counter becomes smaller than 0, the need_resched field of the process descriptor is set to 1. In this case, the schedule( ) function is invoked before resuming User Mode execution, and other TASK_RUNNING processes will have a chance to resume execution on the CPU. I l@ve RuBoard I l@ve RuBoard 6.4 Updating the Time and Date User programs get the current time and date from the xtime variable of type struct timeval. The kernel also occasionally refers to it, for instance, when updating inode timestamps (see Section 1.5.4). In particular, xtime.tv_sec stores the number of seconds that have elapsed since midnight of January 1, 1970 (UTC), while xtime.tv_usec stores the number of microseconds that have elapsed within the last second (its value ranges between 0 and 999999). During kernel initialization, the time_init( ) function is invoked to set up the time and date. It reads them from the Real Time Clock by invoking the get_cmos_time( ) function, then it initializes xtime. Once this has been done, the kernel does not need the RTC anymore; it relies instead on the TIMER_BH bottom half, which is usually activated once every tick. The update_times( ) function is equivalent to the following: void update_times(void) { unsigned long ticks; write_lock_irq(&xtime_lock); ticks = jiffies - wall_jiffies; if (ticks) { wall_jiffies += ticks; update_wall_time(ticks); } write_unlock_irq(&xtime_lock); calc_load(ticks); } On a uniprocessor system, the write_lock_irq( ) and write_unlock_irq( ) functions simply disable and enable the interrupts on the executing CPU; on multiprocessor systems, they also acquire and release the xtime_lock spin lock, which protects against concurrent accesses to the xtime variable. The wall_jiffies variable stores the time of the last update of the xtime variable. Observe that the value of wall_jiffies can be smaller than jiffies-1, since the execution of the bottom half can be delayed; in other words, the kernel does not necessarily update the xtime variable at every tick. However, no tick is definitively lost, and in the long run, xtime stores the correct system time. The update_wall_time( ) function invokes the update_wall_time_one_tick( ) function ticks consecutive times; each invocation adds 10,000 to the xtime.tv_usec field.[5] If xtime.tv_usec becomes greater than 999,999, the update_wall_time( ) function also updates the tv_sec field of xtime. [5] In fact, the function is much more complex since it might tune the value 10,000 slightly. This may be necessary if an adjtimex( ) system call has been issued (see Section 6.7.2 later in this chapter). I l@ve RuBoard I l@ve RuBoard 6.5 Updating System Statistics The kernel, among the other time-related duties, must periodically collect several data used to: ● Checking the CPU resource limit of the running processes ● Computing the average system load ● Profiling the kernel code 6.5.1 Checking the Current Process CPU Resource Limit The update_process_times( ) function (invoked by either the PIT's timer interrupt handler on uniprocessor systems or the local timer interrupt handler in multiprocessor systems) updates some kernel statistics stored in the kstat variable of type kernel_stat; it then invokes update_one_process( ) to update some fields storing statistics that can be exported to user programs through the times( ) system call. In particular, a distinction is made between CPU time spent in User Mode and in Kernel Mode. The function performs the following actions: 1. Updates the per_cpu_utime field of current's process descriptor, which stores the number of ticks during which the process has been running in User Mode. 2. Updates the per_cpu_stime field of current's process descriptor, which stores the number of ticks during which the process has been running in Kernel Mode. 3. Invokes do_process_times( ), which checks whether the total CPU time limit has been reached; if so, it sends SIGXCPU and SIGKILL signals to current. Section 3.2.5 describes how the limit is controlled by the rlim[RLIMIT_CPU].rlim_cur field of each process descriptor. Two additional fields called times.tms_cutime and times.tms_cstime are provided in the process descriptor to count the number of CPU ticks spent by the process children in User Mode and Kernel Mode, respectively. For reasons of efficiency, these fields are not updated by update_one_process( ), but rather when the parent process queries the state of one of its children (see Section 3.5). 6.5.2 Keeping Track of System Load Any Unix kernel keeps track of how much CPU activity is being carried on by the system. These statistics are used by various administration utilities such as top. A user who enters the uptime command sees the statistics as the "load average" relative to the last minute, the last 5 minutes, and the last 15 minutes. On a uniprocessor system, a value of 0 means that there are no active processes (besides the swapper process 0) to run, while a value of 1 means that the CPU is 100 percent busy with a single process, and values greater than 1 mean that the CPU is shared among several active processes.[6] [6] Linux includes in the load average all processes that are in TASK_RUNNING and TASK_UNINTERRUPTIBLE states. However, in normal conditions, there are few TASK_UNINTERRUPTIBLE processes, so a high load usually means that the CPU is busy. The system load data is collected by the calc_load( ) function, which is invoked by update_times( ). This activity is therefore performed in the TIMER_BH bottom half. calc_load( ) counts the number of processes in the TASK_RUNNING or TASK_UNINTERRUPTIBLE state and uses this number to update the CPU usage statistics. 6.5.3 Profiling the Kernel Code Linux includes a minimalist code profiler used by Linux developers to discover where the kernel spends its time in Kernel Mode. The profiler identifies the hot spots of the kernel — the most frequently executed fragments of kernel code. Identifying the kernel hot spots is very important because they may point out kernel functions that should be further optimized. The profiler is based on a very simple Monte Carlo algorithm: at every timer interrupt occurrence, the kernel determines whether the interrupt occurred in Kernel Mode; if so, the kernel fetches the value of the eip register before the interruption from the stack and uses it to discover what the kernel was doing before the interrupt. In the long run, the samples accumulate on the hot spots. The x86_do_profile( ) function collects the data for the code profiler. It is invoked either by the do_timer_interrupt( ) function in uniprocessor systems (by the PIT's timer interrupt handler) or by the smp_local_timer_interrupt( ) function in multiprocessor systems (by the local timer interrupt handler). To enable the code profiler, the Linux kernel must be booted by passing as a parameter the string profile=N, where 2N denotes the size of the code fragments to be profiled. The collected data can be read from the /proc/profile file. The counters are reset by writing in the same file; in multiprocessor systems, writing into the file can also change the sample frequency (see the earlier section Section 6.2.2). However, kernel developers do not usually access /proc/profile directly; instead, they use the readprofile system command. 6.5.4 Checking the NMI Watchdogs In multiprocessor systems, Linux offers yet another feature to kernel developers: a watchdog system, which might be quite useful to detect kernel bugs that cause a system freeze. To activate such watchdog, the kernel must be booted with the nmi_watchdog parameter. The watchdog is based on a clever hardware feature of multiprocessor motherboards: they can broadcast the PIT's interrupt timer as NMI interrupts to all CPUs. Since NMI interrupts are not masked by the cli assembly language instruction, the watchdog can detect deadlocks even when interrupts are disabled. As a consequence, once every tick, all CPUs, regardless of what they are doing, start executing the NMI interrupt handler; in turn, the handler invokes do_nmi( ). This function gets the logical number n of the CPU, and then checks the nth entry of the apic_timer_irqs array. If the CPU is working properly, the value must be different from the value read at the previous NMI interrupt. When the CPU is running properly, the nth entry of the apic_timer_irqs array is incremented by the local timer interrupt handler (see the earlier section Section 6.2.2.2); if the counter is not incremented, the local timer interrupt handler has not been executed in a whole tick. Not a good thing, you know. When the NMI interrupt handler detects a CPU freeze, it rings all the bells: it logs scary messages in the system log files, dumps the contents of the CPU registers and of the kernel stack (kernel oops), and finally kills the current process. This gives kernel developers a chance to discover what's gone wrong. I l@ve RuBoard I l@ve RuBoard 6.6 Software Timers A timer is a software facility that allows functions to be invoked at some future moment, after a given time interval has elapsed; a time-out denotes a moment at which the time interval associated with a timer has elapsed. Timers are widely used both by the kernel and by processes. Most device drivers use timers to detect anomalous conditions — floppy disk drivers, for instance, use timers to switch off the device motor after the floppy has not been accessed for a while, and parallel printer drivers use them to detect erroneous printer conditions. Timers are also used quite often by programmers to force the execution of specific functions at some future time (see the later section Section 6.7.3). Implementing a timer is relatively easy. Each timer contains a field that indicates how far in the future the timer should expire. This field is initially calculated by adding the right number of ticks to the current value of jiffies. The field does not change. Every time the kernel checks a timer, it compares the expiration field to the value of jiffies at the current moment, and the timer expires when jiffies is greater or equal to the stored value. This comparison is made via the time_after, time_before, time_after_eq, and time_before_eq macros, which take care of possible overflows of jiffies. Linux considers two types of timers called dynamic timers and interval timers. The first type is used by the kernel, while interval timers may be created by processes in User Mode.[7] [7] Earlier versions of Linux use a third type of kernel timers: the so-called static timers. Static timers are very rudimental because they cannot be dynamically allocated or destroyed, and at most there could be 32 of them. Static timers were replaced by dynamic timers, and new kernels (starting from Version 2.4) no longer support them. One word of caution about Linux timers: since checking for timer functions is always done by bottom halves that may be executed a long time after they have been activated, the kernel cannot ensure that timer functions will start right at their expiration times. It can only ensure that they are executed either at the proper time or after with a delay of up to a few hundreds of milliseconds. For this reason, timers are not appropriate for real-time applications in which expiration times must be strictly enforced. 6.6.1 Dynamic Timers Dynamic timers may be dynamically created and destroyed. No limit is placed on the number of currently active dynamic timers. A dynamic timer is stored in the following timer_list structure: struct timer_list { struct list_head list; unsigned long expires; unsigned long data; void (*function)(unsigned long); }; The function field contains the address of the function to be executed when the timer expires. The data field specifies a parameter to be passed to this timer function. Thanks to the data field, it is possible to define a single general-purpose function that handles the time-outs of several device drivers; the data field could store the device ID or other meaningful data that could be used by the function to differentiate the device. The expires field specifies when the timer expires; the time is expressed as the number of ticks that have elapsed since the system started up. All timers that have an expires value smaller than or equal to the value of jiffies are considered to be expired or decayed. The list field includes the links for a doubly linked circular list. There are 512 doubly linked circular lists to hold dynamic timers. Each timer is inserted into one of the lists based on the value of the expires field. The algorithm that uses this list is described later in this chapter. To create and activate a dynamic timer, the kernel must: 1. Create a new timer_list object — for example, t. This can be done in several ways by: ❍ Defining a static global variable in the code. ❍ Defining a local variable inside a function; in this case, the object is stored on the Kernel Mode stack. ❍ Including the object in a dynamically allocated descriptor. 2. Initialize the object by invoking the init_timer(&t) function. This simply sets the links in the list field to NULL. 3. Load the function field with the address of the function to be activated when the timer decays. If required, load the data field with a parameter value to be passed to the function. 4. If the dynamic timer is not already inserted in a list, assign a proper value to the expires field. Otherwise, update the expires field by invoking the mod_timer( ) function, which also takes care of moving the object into the proper list (discussed shortly). 5. If the dynamic timer is not already inserted in a list, insert the t element in the proper list by invoking the add_timer(&t) function. Once the timer has decayed, the kernel automatically removes the t element from its list. Sometimes, however, a process should explicitly remove a timer from its list using the del_timer( ) or del_timer_sync( ) functions. Indeed, a sleeping process may be woken up before the time-out is over; in this case, the process may choose to destroy the timer. Invoking del_timer( ) or del_timer_sync( ) on a timer already removed from a list does no harm, so removing the timer within the timer function is considered a good practice. 6.6.1.1 Dynamic timers and race conditions Being asynchronously activated, dynamic timers are prone to race conditions. For instance, consider a dynamic timer whose function acts on a discardable resource (e.g., a kernel module or a file data structure). Releasing the resource without stopping the timer may lead to data corruption if the timer function got activated when the resource no longer exists. Thus, a rule of thumb is to stop the timer before releasing the resource: ... del_timer(&t); X_Release_Resources( ); ... In multiprocessor systems, however, this code is not safe because the timer function might already be running on another CPU when del_timer( ) is invoked. As a result, resources may be released while the timer function is still acting on them. To avoid this kind of race condition, the kernel offers the del_timer_sync( ) function. It removes the timer from the list, and then it checks whether the timer function is executed on another CPU; in such a case, del_timer_sync( ) waits until the timer function terminates. Other types of race conditions exist, of course. For instance, the right way to modify the expires field of an already activated timer consists of using mod_timer( ), rather than deleting the timer and recreating it thereafter. In the latter approach, two kernel control paths that want to modify the expires field of the same timer may mix each other up badly. The implementation of the timer functions is made SMP-safe by means of the timerlist_lock spin lock: every time the kernel must access the lists of dynamic timers, it disables the interrupts and acquires this spin lock. 6.6.1.2 Dynamic timers handling Choosing the proper data structure to implement dynamic timers is not easy. Stringing together all timers in a single list would degrade system performances, since scanning a long list of timers at every tick is costly. On the other hand, maintaining a sorted list would not be much more efficient, since the insertion and deletion operations would also be costly. The adopted solution is based on a clever data structure that partitions the expires values into blocks of ticks and allows dynamic timers to percolate efficiently from lists with larger expires values to lists with smaller ones. The main data structure is an array called tvecs, whose elements point to five groups of lists identified by the tv1, tv2, tv3, tv4, and tv5 structures (see Figure 6-2). Figure 6-2. The groups of lists associated with dynamic timers The tv1 structure is of type struct timer_vec_root, which includes an index field and a vec array of 256 list_head elements — that is, lists of dynamic timers. It contains all dynamic timers that will decay within the next 255 ticks. The index field specifies the currently scanned list; it is initialized to 0 and incremented by 1 (modulo 256) at every tick. The list referenced by index contains all dynamic timers that expired during the current tick; the next list contains all dynamic timers that will expire in the next tick; the (index+k)th list contains all dynamic timers that will expire in exactly k ticks. When index returns to 0, it signifies that all the timers in tv1 have been scanned. In this case, the list pointed to by tv2.vec[tv2.index] is used to replenish tv1. The tv2, tv3, and tv4 structures of type struct timer_vec contain all dynamic timers that will decay within the next 214-1, 220-1, and 226-1 ticks, respectively. The tv5 structure is identical to the previous ones, except that the last entry of the vec array includes dynamic timers with extremely large expires fields. It never needs to be replenished from another array. The timer_vec structure is very similar to timer_vec_root: it contains an index field and a vec array of 64 pointers to dynamic timer lists. The index field specifies the currently scanned list; it is incremented by 1 (modulo 64) every 256i-1 ticks, where i, ranging between 2 and 5, is the tvi group number. As in the case of tv1, when index returns to 0, the list pointed to by tvj.vec[tvj.index] is used to replenish tvi (i ranges between 2 and 4, j is equal to i+1). Thus, the first element of tv2 holds a list of all timers that expire in the 256 ticks following the tv1 timers; the timers in this list are sufficient to replenish the whole array tv1. The second element of tv2 holds all timers that expire in the following 256 ticks, and so on. Similarly, a single entry of tv3 is sufficient to replenish the whole array tv2. Figure 6-2 shows how these data structures are connected. The timer_bh( ) function associated with the TIMER_BH bottom half invokes the run_timer_list( ) auxiliary function to check for decayed dynamic timers. The function relies on a variable similar to jiffies that is called timer_jiffies. This new variable is needed because a few timer interrupts might occur before the activated TIMER_BH bottom half has a chance to run; this happens typically when several interrupts of different types are issued in a short interval of time. The value of timer_jiffies represents the expiration time of the dynamic timer list yet to be checked: if it coincides with the value of jiffies, no backlog of bottom half functions has accumulated; if it is smaller than jiffies, then bottom half functions that refer to previous ticks must be dealt with. The variable is set to 0 at system startup and is incremented only by run_timer_list( ). Its value can never be greater than jiffies. The run_timer_list( ) function is essentially equivalent the following C fragment: struct list_head *head, *curr; struct timer_list *timer; void (*fn)(unsigned long); unsigned long data; spin_lock_irq(&timerlist_lock); while ((long)(jiffies - timer_jiffies) >= 0) { if (!tv1.index) { int n = 1; do { cascade_timers(tvecs[n]); } while (tvecs[n]->index == 1 && ++n < 5)); } head = &tv1.vec[tv1.index]; for (curr = head->next; curr != head; curr = head->next) { timer = list_entry(curr, struct timer_list, list); fn = timer->function; data= timer->data; detach_timer(timer); timer->list.next = timer->list.prev = NULL; running_timer = timer; spin_unlock_irq(&timerlist_lock); fn(data); spin_lock_irq(&timerlist_lock); running_timer = NULL; } ++timer_jiffies; tv1.index = (tv1.index + 1) & 0xff; } spin_unlock_irq(&timerlist_lock); The outermost while loop ends when timer_jiffies becomes greater than the value of jiffies. Since the values of jiffies and timer_jiffies usually coincide, the outermost while cycle is often executed only once. In general, the outermost loop is executed jiffies - timer_jiffies + 1 consecutive times. Moreover, if a timer interrupt occurs while run_timer_list( ) is being executed, dynamic timers that decay at this tick occurrence are also considered, since the jiffies variable is asynchronously incremented by the PIT's interrupt handler (see the earlier section Section 6.2.1.1). During a single execution of the outermost while cycle, the dynamic timer functions included in the tv1.vec[tv1.index] list are executed. Before executing a dynamic timer function, the loop invokes the detach_timer( ) function to remove the dynamic timer from the list. Once the list is emptied, the value of tv1.index is incremented (modulo 256) and the value of timer_jiffies is incremented. When tv1.index becomes equal to 0, all the lists of tv1 have been checked; in this case, it is necessary to refill the tv1 structure. This is accomplished by the cascade_timers( ) function, which transfers the dynamic timers included in tv2.vec[tv2.index] into tv1.vec, since they will necessarily decay within the next 256 ticks. If tv2.index is equal to 0, the tv2 array of lists must be refilled with the elements of tv3.vec[tv3.index]. Notice that run_timer_list( ) disables interrupts and acquires the timerlist_lock spin lock just before entering the outermost loop; interrupts are enabled and the spin lock is released right before invoking each dynamic timer function, until its termination. This ensures that the dynamic timer data structures are not corrupted by interleaved kernel control paths. To sum up, this rather complex algorithm ensures excellent performance. To see why, assume for the sake of simplicity that the TIMER_BH bottom half is executed right after the corresponding timer interrupt occurs. Then, in 255 timer interrupt occurrences out of 256 (in 99.6% of the cases), the run_timer_list( ) function just runs the functions of the decayed timers, if any. To replenish tv1.vec periodically, it is sufficient 63 times out of 64 to partition the list pointed to by tv2.vec[tv2.index] into the 256 lists pointed to by tv1.vec. The tv2.vec array, in turn, must be replenished in 0.02 percent of the cases (that is, once every 163 seconds). Similarly, tv3 is replenished every 2 hours and 54 minutes, and tv4 is replenished every 7 days and 18 hours. tv5 doesn't need to be replenished. 6.6.2 An Application of Dynamic Timers To show how the outcome of all the previous activities are actually used in the kernel, we'll show an example of the creation and use of a process time-out. Let's assume that the kernel decides to suspend the current process for two seconds. It does this by executing the following code: timeou = 2 * HZ; set_current_state(TASK_INTERRUPTIBLE); /* or TASK_UNINTERRUPTIBLE */ remaining = schedule_timeout(timeout); The kernel implements process time-outs by using dynamic timers. They appear in the schedule_timeout( ) function, which essentially executes the following statements: struct timer_list timer; expire = timeout + jiffies; init_timer(&timer); timer.expires = expire; timer.data = (unsigned long) current; timer.function = process_timeout; add_timer(&timer); schedule( ); /* process suspended until timer expires */ del_timer_sync(&timer); timeout = expire - jiffies; return (timeout < 0 ? 0 : timeout); When schedule( ) is invoked, another process is selected for execution; when the former process resumes its execution, the function removes the dynamic timer. In the last statement, the function either returns 0, if the time-out is expired, or it returns the number of ticks left to the time-out expiration if the process was awoken for some other reason. When the time-out expires, the kernel executes the following function: void process_timeout(unsigned long data) { struct task_struct * p = (struct task_struct *) data; wake_up_process(p); } The run_timer_list( ) function invokes process_timeout( ), passing as its parameter the process descriptor pointer stored in the data field of the timer object. As a result, the suspended process is woken up. I l@ve RuBoard I l@ve RuBoard 6.7 System Calls Related to Timing Measurements Several system calls allow User Mode processes to read and modify the time and date and to create timers. Let's briefly review these and discuss how the kernel handles them. 6.7.1 The time( ), ftime( ), and gettimeofday( ) System Calls Processes in User Mode can get the current time and date by means of several system calls: time( ) Returns the number of elapsed seconds since midnight at the start of January 1, 1970 (UTC). ftime( ) Returns, in a data structure of type timeb, the number of elapsed seconds since midnight of January 1, 1970 (UTC) and the number of elapsed milliseconds in the last second. gettimeofday( ) Returns, in a data structure named timeval, the number of elapsed seconds since midnight of January 1, 1970 (UTC) (a second data structure named timezone is not currently used). The former system calls are superseded by gettimeofday( ), but they are still included in Linux for backward compatibility. We don't discuss them further. The gettimeofday( ) system call is implemented by the sys_gettimeofday( ) function. To compute the current date and time of the day, this function invokes do_gettimeofday( ), which executes the following actions: 1. Disables the interrupts and acquires the xtime_lock read/write spin lock for reading. 2. Gets the number of microseconds elapsed in the last second by using the function whose address is stored in do_gettimeoffset: usec = do_gettimeoffset( ); If the CPU has a Time Stamp Counter, the do_fast_gettimeoffset( ) function is executed. It reads the TSC register by using the rdtsc assembly language instruction; it then subtracts the value stored in last_tsc_low to obtain the number of CPU cycles elapsed since the last timer interrupt was handled. The function converts that number to microseconds and adds in the delay that elapsed before the activation of the timer interrupt handler (stored in the delay_at_last_interrupt variable mentioned earlier in Section 6.2.1.1). If the CPU does not have a TSC register, do_gettimeoffset points to the do_slow_gettimeoffset( ) function. It reads the state of the 8254 chip device internal oscillator and then computes the time length elapsed since the last timer interrupt. Using that value and the contents of jiffies, it can derive the number of microseconds elapsed in the last second. 3. Further increases the number of microseconds in order to take into account all timer interrupts whose bottom halves have not yet been executed: usec += (jiffies - wall_jiffies) * (1000000/HZ); 4. Copies the contents of xtime into the user-space buffer specified by the system call parameter tv, adding to the following fields: tv->tv_sec = xtime->tv_sec; tv->tv_usec = xtime->tv_usec + usec; 5. Releases the xtime_lock spin lock and reenables the interrupts. 6. Checks for an overflow in the microseconds field, adjusting both that field and the second field if necessary: while (tv->tv_usec >= 1000000) { tv->tv_usec -= 1000000; tv->tv_sec++; } Processes in User Mode with root privilege may modify the current date and time by using either the obsolete stime( ) or the settimeofday( ) system call. The sys_settimeofday( ) function invokes do_settimeofday( ), which executes operations complementary to those of do_gettimeofday( ). Notice that both system calls modify the value of xtime while leaving the RTC registers unchanged. Therefore, the new time is lost when the system shuts down, unless the user executes the clock program to change the RTC value. 6.7.2 The adjtimex( ) System Call Although clock drift ensures that all systems eventually move away from the correct time, changing the time abruptly is both an administrative nuisance and risky behavior. Imagine, for instance, programmers trying to build a large program and depending on filetime stamps to make sure that out-of-date object files are recompiled. A large change in the system's time could confuse the make program and lead to an incorrect build. Keeping the clocks tuned is also important when implementing a distributed filesystem on a network of computers. In this case, it is wise to adjust the clocks of the interconnected PCs so that the timestamp values associated with the inodes of the accessed files are coherent. Thus, systems are often configured to run a time synchronization protocol such as Network Time Protocol (NTP) on a regular basis to change the time gradually at each tick. This utility depends on the adjtimex( ) system call in Linux. This system call is present in several Unix variants, although it should not be used in programs intended to be portable. It receives as its parameter a pointer to a timex structure, updates kernel parameters from the values in the timex fields, and returns the same structure with current kernel values. Such kernel values are used by update_wall_time_one_tick( ) to slightly adjust the number of microseconds added to xtime.tv_usec at each tick. 6.7.3 The setitimer( ) and alarm( ) System Calls Linux allows User Mode processes to activate special timers called interval timers.[8] [8] These software constructs have nothing in common with the Programmable Interval Timer chips described earlier in this chapter. The timers cause Unix signals (see Chapter 10) to be sent periodically to the process. It is also possible to activate an interval timer so that it sends just one signal after a specified delay. Each interval timer is therefore characterized by: ● The frequency at which the signals must be emitted, or a null value if just one signal has to be generated ● The time remaining until the next signal is to be generated The earlier warning about accuracy applies to these timers. They are guaranteed to execute after the requested time has elapsed, but it is impossible to predict exactly when they will be delivered. Interval timers are activated by means of the POSIX setitimer( ) system call. The first parameter specifies which of the following policies should be adopted: ITIMER_REAL The actual elapsed time; the process receives SIGALRM signals. ITIMER_VIRTUAL The time spent by the process in User Mode; the process receives SIGVTALRM signals. ITIMER_PROF The time spent by the process both in User and in Kernel Mode; the process receives SIGPROF signals. To implement an interval timer for each of the preceding policies, the process descriptor includes three pairs of fields: ● it_real_incr and it_real_value ● it_virt_incr and it_virt_value ● it_prof_incr and it_prof_value The first field of each pair stores the interval in ticks between two signals; the other field stores the current value of the timer. The ITIMER_REAL interval timer is implemented by using dynamic timers because the kernel must send signals to the process even when it is not running on the CPU. Therefore, each process descriptor includes a dynamic timer object called real_timer. The setitimer( ) system call initializes the real_timer fields and then invokes add_timer( ) to insert the dynamic timer in the proper list. When the timer expires, the kernel executes the it_real_fn( ) timer function. In turn, the it_real_fn( ) function sends a SIGALRM signal to the process; if it_real_incr is not null, it sets the expires field again, reactivating the timer. The ITIMER_VIRTUAL and ITIMER_PROF interval timers do not require dynamic timers, since they can be updated while the process is running. The do_it_virt( ) and do_it_prof( ) functions are invoked by update_one_ process( ), which is called either by the PIT's timer interrupt handler (UP) or by the local timer interrupt handlers (SMP). Therefore, the two interval timers are updated once every tick, and if they are expired, the proper signal is sent to the current process. The alarm( ) system call sends a SIGALRM signal to the calling process when a specified time interval has elapsed. It is very similar to setitimer( ) when invoked with the ITIMER_REAL parameter, since it uses the real_timer dynamic timer included in the process descriptor. Therefore, alarm( ) and setitimer( ) with parameter ITIMER_REAL cannot be used at the same time. I l@ve RuBoard I l@ve RuBoard Chapter 7. Memory Management We saw in Chapter 2 how Linux takes advantage of 80 x 86's segmentation and paging circuits to translate logical addresses into physical ones. We also mentioned that some portion of RAM is permanently assigned to the kernel and used to store both the kernel code and the static kernel data structures. The remaining part of the RAM is called dynamic memory. It is a valuable resource, needed not only by the processes but also by the kernel itself. In fact, the performance of the entire system depends on how efficiently dynamic memory is managed. Therefore, all current multitasking operating systems try to optimize the use of dynamic memory, assigning it only when it is needed and freeing it as soon as possible. This chapter, which consists of three main sections, describes how the kernel allocates dynamic memory for its own use. Section 7.1 and Section 7.2 illustrate two different techniques for handling physically contiguous memory areas, while Section 7.3 illustrates a third technique that handles noncontiguous memory areas. I l@ve RuBoard I l@ve RuBoard 7.1 Page Frame Management We saw in Section 2.4 how the Intel Pentium processor can use two different page frame sizes: 4 KB and 4 MB (or 2 MB if PAE is enabled—see Section 2.4.6). Linux adopts the smaller 4 KB page frame size as the standard memory allocation unit. This makes things simpler for two reasons: ● The Page Fault exceptions issued by the paging circuitry are easily interpreted. Either the page requested exists but the process is not allowed to address it, or the page does not exist. In the second case, the memory allocator must find a free 4 KB page frame and assign it to the process. ● The 4 KB size is a multiple of most disk block sizes, so transfers of data between main memory and disks are more efficient. Yet this smaller size is much more manageable than the 4 MB size. 7.1.1 Page Descriptors The kernel must keep track of the current status of each page frame. For instance, it must be able to distinguish the page frames that are used to contain pages that belong to processes from those that contain kernel code or kernel data structures. Similarly, it must be able to determine whether a page frame in dynamic memory is free. A page frame in dynamic memory is free if it does not contain any useful data. It is not free when the page frame contains data of a User Mode process, data of a software cache, dynamically allocated kernel data structures, buffered data of a device driver, code of a kernel module, and so on. State information of a page frame is kept in a page descriptor of type struct page, whose fields are shown in Table 7-1. All page descriptors are stored in the mem_map array. Since each descriptor is less than 64 bytes long, mem_map requires about four page frames for each megabyte of RAM. Table 7-1. The fields of the page descriptor Type Name Description struct list_head list Contains pointers to next and previous items in a doubly linked list of page descriptors struct address_space * mapping Used when the page is inserted into the page cache (see Section 14.1) unsigned long index Either the position of the data stored in the page within the page's disk image (see Chapter 14) or a swapped-out page identifier (see Chapter 16) struct page * next_hash Contains pointer to next item in a doubly linked circular list of the page cache hash table atomic_t count Page's reference counter unsigned long flags Array of flags (see Table 7-2) struct list_head lru Contains pointers to the least recently used doubly linked list of pages wait_queue_head_t wait Page's wait queue struct page * * pprev_hash Contains pointer to previous item in a doubly linked circular list of the page cache hash table struct buffer_head * buffers Used when the page stores buffers (see Section 13.4.8.2) void * virtual Linear address of the page frame in the fourth gigabyte (see Section 7.1.5 later in this chapter) struct zone_struct * zone The zone to which the page frame belongs (see Section 7.1.2) You don't have to fully understand the role of all fields in the page descriptor right now. In the following chapters, we often come back to the fields of the page descriptor. Moreover, several fields have different meaning, according to whether the page frame is free and what kernel component is using the page frame. Let's describe in greater detail two of the fields: count A usage reference counter for the page. If it is set to 0, the corresponding page frame is free and can be assigned to any process or to the kernel itself. If it is set to a value greater than 0, the page frame is assigned to one or more processes or is used to store some kernel data structures. flags Includes up to 32 flags (see Table 7-2) that describe the status of the page frame. For each PG_xyz flag, the kernel defines some macros that manipulate its value. Usually, the PageXyz macro returns the value of the flag, while the SetPageXyz and ClearPageXyz macro set and clear the corresponding bit, respectively. Table 7-2. Flags describing the status of a page frame Flag name Meaning PG_locked The page is involved in a disk I/O operation. PG_error An I/O error occurred while transferring the page. PG_referenced The page has been recently accessed for a disk I/O operation. PG_uptodate The flag is set after completing a read operation, unless a disk I/O error happened. PG_dirty The page has been modified (see Section 16.5.1). PG_lru The page is in the active or inactive page list (see Section 16.7.2). PG_active The page is in the active page list (see Section 16.7.2). PG_slab The page frame is included in a slab (see Section 7.2 later in this chapter). PG_skip Not used. PG_highmem The page frame belongs to the ZONE_HIGHMEM zone (see Section 7.1.2). PG_checked The flag used by the Ext2 filesystem (see Chapter 17). PG_arch_1 Not used on the 80 x 86 architecture. PG_reserved The page frame is reserved to kernel code or is unusable. PG_launder The page is involved in an I/O operation triggered by shrink_cache( ) (see Section 16.7.5). 7.1.2 Memory Zones In an ideal computer architecture, a page frame is a memory storage unit that can be used for anything: storing kernel and user data, buffering disk data, and so on. Any kind of page of data can be stored in any page frame, without limitations. However, real computer architectures have hardware constraints that may limit the way page frames can be used. In particular, the Linux kernel must deal with two hardware constraints of the 80 x 86 architecture: ● The Direct Memory Access (DMA) processors for ISA buses have a strong limitation: they are able to address only the first 16 MB of RAM. ● In modern 32-bit computers with lots of RAM, the CPU cannot directly access all physical memory because the linear address space is too small. To cope with these two limitations, Linux partitions the physical memory in three zones: ZONE_DMA Contains pages of memory below 16 MB ZONE_NORMAL Contains pages of memory at and above 16 MB and below 896 MB ZONE_HIGHMEM Contains pages of memory at and above 896 MB The ZONE_DMA zone includes memory pages that can be used by old ISA-based devices by means of the DMA. (Section 13.1.4 gives further details on DMA.) The ZONE_DMA and ZONE_NORMAL zones include the "normal" pages of memory that can be directly accessed by the kernel through the linear mapping in the fourth gigabyte of the linear address space (see Section 2.5.5). Conversely, the ZONE_HIGHMEM zone includes pages of memory that cannot be directly accessed by the kernel through the linear mapping in the fourth gigabyte of linear address space (see Section 7.1.6 later in this chapter). The ZONE_HIGHMEM zone is not used on 64-bit architectures. Each memory zone has its own descriptor of type struct zone_struct (or equivalently, zone_t). Its fields are shown in Table 7-3. Table 7-3. The fields of the zone descriptor Type Name Description char * name Contains a pointer to the conventional name of the zone: "DMA," "Normal," or "HighMem" unsigned long size Number of pages in the zone spinlock_t lock Spin lock protecting the descriptor unsigned long free_pages Number of free pages in the zone unsigned long pages_min Minimum number of pages of the zone that should remain free (see Section 16.7) unsigned long pages_low Lower threshold value for the zone's page balancing algorithm (see Section 16.7) unsigned long pages_high Upper threshold value for the zone's page balancing algorithm (see Section 16.7) int need_balance Flag indicating that the zone's page balancing algorithm should be activated (see Section 16.7) free_area_t [ ] free_area Used by the buddy system page allocator (see the later section Section 7.1.7) struct pglist_data * zone_pgdat Pointer to the descriptor of the node to which this zone belongs struct page * zone_mem_map Array of page descriptors of the zone (see the later section Section 7.1.7) unsigned long zone_start_paddr First physical address of the zone unsigned long zone_start_mapnr First page descriptor index of the zone The zone field in the page descriptor points to the descriptor of the zone to which the corresponding page frame belongs. The zone_names array stores the canonical names of the three zones: "DMA," "Normal," and "HighMem." When the kernel invokes a memory allocation function, it must specify the zones that contain the requested page frames. The kernel usually specifies which zones it's willing to use. For instance, if a page frame must be directly mapped in the fourth gigabyte of linear addresses but it is not going to be used for ISA DMA transfers, then the kernel requests a page frame either in ZONE_NORMAL or in ZONE_DMA. Of course, the page frame should be obtained from ZONE_DMA only if ZONE_NORMAL does not have free page frames. To specify the preferred zones in a memory allocation request, the kernel uses the struct zonelist_struct data structure (or equivalently zonelist_t), which is an array of zone descriptor pointers. 7.1.3 Non-Uniform Memory Access (NUMA) We are used to thinking of the computer's memory as an homogeneous, shared resource. Disregarding the role of the hardware caches, we expect the time required for a CPU to access a memory location is essentially the same, regardless of the location's physical address and the CPU. Unfortunately, this assumption is not true in some architectures. For instance, it is not true for some multiprocessor Alpha or MIPS computers. Linux 2.4 supports the Non-Uniform Memory Access (NUMA) model, in which the access times for different memory locations from a given CPU may vary. The physical memory of the system is partitioned in several nodes. The time needed by any given CPU to access pages within a single node is the same. However, this time might not be the same for two different CPUs. For every CPU, the kernel tries to minimize the number of accesses to costly nodes by carefully selecting where the kernel data structures that are most often referenced by the CPU are stored. The physical memory inside each node can be split in several zones, as we saw in the previous section. Each node has a descriptor of type pg_data_t, whose fields are shown in Table 7-4. All node descriptors are stored in a simply linked list, whose first element is pointed to by the pgdat_list variable. Table 7-4. The fields of the node descriptor Type Name Description zone_t [ ] node_zones Array of zone descriptors of the node zonelist_t [ ] node_zonelists Array of zonelist_t data structures used by the page allocator (see the later section Section 7.1.5) int nr_zones Number of zones in the node struct page * node_mem_map Array of page descriptors of the node unsigned long * valid_addr_bitmap Bitmap of usable physical addresses for the node struct bootmem_data x* bdata Used in the kernel initialization phase unsigned long node_start_paddr First physical address of the node unsigned long node_start_mapnr First page descriptor index of the node unsigned long node_size Size of the node (in pages) int node_id Identifier of the node pg_data_t * node_next Next item in the node list As usual, we are mostly concerned with the 80 x 86 architecture. IBM-compatible PCs use the Uniform Access Memory model (UMA), thus the NUMA support is not really required. However, even if NUMA support is not compiled in the kernel, Linux makes use of a single node that includes all system physical memory; the corresponding descriptor is stored in the contig_page_data variable. On the 80 x 86 architecture, grouping the physical memory in a single node might appear useless; however, this approach makes the memory handling code more portable, because the kernel may assume that the physical memory is partitioned in one or more nodes in all architectures.[1] [1] We have another example of this kind of design choice: Linux uses three levels of Page Tables even when the hardware architecture defines just two levels (see Section 2.5). 7.1.4 Initialization of the Memory Handling Data Structures Dynamic memory and the values used to refer to it are illustrated in Figure 7-1. The zones of memory are now drawn to scale; ZONE_NORMAL is usually larger than ZONE_DMA, and, if present, ZONE_HIGHMEM is usually larger than ZONE_NORMAL. Notice that ZONE_HIGHMEM starts from physical address 0x38000000, which corresponds to 896 MB. Figure 7-1. Memory layout We already described how the paging_init( ) function initializes the kernel Page Tables according to the amount of RAM in the system in Section 2.5.5. Beside Page Tables, the paging_init( ) function also initializes other memory handling data structures. It invokes kmap_init( ), which essentially sets up the kmap_pte variable to create "windows" of linear addresses that allow the kernel to address the ZONE_HIGHMEM zone (see Section 7.1.6.2 later in this chapter). Then, paging_init( ) invokes the free_area_init( ) function, passing an array storing the sizes of the three memory zones to it. The free_area_init( ) function sets up both the zone descriptors and the page descriptors. The function receives the zones_size array (size of each memory zone) as its parameter, and executes the following operations:[2] [2] In NUMA architectures, these operations must be performed separately on every node. However, we are focusing on the 80 x 86 architecture, which has just one node. 1. Computes the total number of page frames in RAM by adding the value in zones_size, and stores the result in the totalpages local variable. 2. Initializes the active_list and inactive_list lists of page descriptors (see Chapter 16). 3. Allocates space for the mem_map array of page descriptors. The space needed is the product of totalpages by the page descriptor size. 4. Initializes some fields of the node descriptor contig_page_data: contig_page_data.node_size = totalpages; contig_page_data.node_start_paddr = 0x00000000; contig_page_data.node_start_mapnr = 0; 5. Initializes some fields of all page descriptors. All page frames are marked as reserved, but later, the PG_reserved flag of the page frames in dynamic memory will be cleared: for (p = mem_map; p < mem_map + totalpages; p++) { p->count = 0; SetPageReserved(p); init_waitqueue_head(&p->wait); p->list.next = p->list.prev = p; } 6. Stores the address of the memory zone descriptor in the zone local variable and for each element of the zone_names array (index j between 0 and 2), performs the following steps: a. Initializes some fields of the descriptor: zone->name = zone_names[j]; zone->size = zones_size[j]; zone->lock = SPIN_LOCK_UNLOCKED; zone->zone_pgdat = & contig_page_data; zone->free_pages = 0; zone->need_balance = 0; b. If the zone is empty (that is, it does not include any page frame), the function goes back to the beginning of Step 6 and continues with the next zone. c. Otherwise, the zone includes at least one page frame and the function initializes the pages_min, pages_low, and pages_high fields of the zone descriptor (see Chapter 16). d. Sets up the zone_mem_map field of the zone descriptor to the address of the first page descriptor in the zone. e. Sets up the zone_start_mapnr field of the zone descriptor to the index of the first page descriptor in the zone. f. Sets up the zone_start_paddr field of the zone descriptor to the physical address of the first page frame in the zone. g. Stores the address of the zone descriptor in the zone field of the page descriptor for each page frame of the zone. h. If the zone is either ZONE_DMA or ZONE_NORMAL, stores the linear address in the fourth gigabyte that maps the page frame into the virtual field of every page descriptor of the zone. i. Initializes the free_area_t structures in the free_area array of the zone descriptor (see Section 7.1.7 later in this chapter). 7. Initializes the node_zonelists array of the contig_page_data node descriptor. The array includes 16 elements; each element corresponds to a different type of memory request and specifies the zones (in order of preference) from where the page frames could be retrieved. See Section 7.1.5 later in this chapter for further details. When the paging_init( ) function terminates, dynamic memory is not yet usable because the PG_reserved flag of all pages is set. Memory initialization is further carried on by the mem_init( ) function, which is invoked subsequently to paging_init( ). Essentially, the mem_init( ) function initializes the value of num_physpages, the total number of page frames present in the system. It then scans all page frames associated with the dynamic memory; for each of them, the function sets the count field of the corresponding descriptor to 1, resets the PG_reserved flag, sets the PG_highmem flag if the page belongs to ZONE_HIGHMEM, and calls the free_ page( ) function on it. Besides releasing the page frame (see Section 7.1.7 later in this chapter), free_page( ) also increments the value of the free_pages field of the memory zone descriptor that owns the page frame. The free_pages fields of all zone descriptors are used by the nr_free_pages( ) function to compute the total number of free page frames in the dynamic memory. The mem_init( ) function also counts the number of page frames that are not associated with dynamic memory. Several symbols produced while compiling the kernel (some are described in Section 2.5.3) enable the function to count the number of page frames reserved for the hardware, kernel code, and kernel data, and the number of page frames used during kernel initialization that can be successively released. 7.1.5 Requesting and Releasing Page Frames After having seen how the kernel allocates and initializes the data structures for page frame handling, we now look at how page frames are allocated and released. Page frames can be requested by using six slightly different functions and macros. Unless otherwise stated, they return the linear address of the first allocated page, or return NULL if the allocation failed. alloc_pages(gfp_mask, order) Function used to request 2order contiguous page frames. It returns the address of the descriptor of the first allocated page frame or returns NULL if the allocation failed. alloc_page(gfp_mask) Macro used to get a single page frame; it expands to: alloc_pages(gfp_mask, 0) It returns the address of the descriptor of the allocated page frame or returns NULL if the allocation failed. _ _get_free_pages(gfp_mask, order) Function that is similar to alloc_pages( ), but it returns the linear address of the first allocated page. _ _get_free_page(gfp_mask) Macro used to get a single page frame; it expands to: _ _get_free_pages(gfp_mask, 0) get_zeroed_page(gfp_mask) , or equivalently get_free_page(gfp_mask) Function that invokes: alloc_pages(gfp_mask, 0) and then fills the page frame obtained with zeros. _ _get_dma_pages(gfp_mask, order) Macro used to get page frames suitable for DMA; it expands to: _ _get_free_pages(gfp_mask | _ _GFP_DMA, order) The parameter gfp_mask specifies how to look for free page frames. It consists of the following flags: _ _GFP_WAIT The kernel is allowed to block the current process waiting for free page frames. _ _GFP_HIGH The kernel is allowed to access the pool of free page frames left for recovering from very low memory conditions. _ _GFP_IO The kernel is allowed to perform I/O transfers on low memory pages in order to free page frames. _ _GFP_HIGHIO The kernel is allowed to perform I/O transfers on high memory pages in order free page frames. _ _GFP_FS The kernel is allowed to perform low-level VFS operations. _ _GFP_DMA The requested page frames must be included in the ZONE_DMA zone (see the earlier section Section 7.1.2.) _ _GFP_HIGHMEM The requested page frames can be included in the ZONE_HIGHMEM zone. In practice, Linux uses the predefined combinations of flag values shown in Table 7-5; the group name is what you'll encounter as argument of the six page frame allocation functions. Table 7-5. Groups of flag values used to request page frames Group name Corresponding flags GFP_ATOMIC _ _GFP_HIGH GFP_NOIO _ _GFP_HIGH _ _GFP_WAIT GFP_NOHIGHIO _ _GFP_HIGH _ _GFP_WAIT _ _GFP_IO GFP_NOFS _ _GFP_HIGH _ _GFP_WAIT _ _GFP_IO _ _GFP_HIGHIO GFP_KERNEL _ _GFP_HIGH _ _GFP_WAIT _ _GFP_IO _ _GFP_HIGHIO _ _GFP_FS GFP_NFS _ _GFP_HIGH _ _GFP_WAIT _ _GFP_IO _ _GFP_HIGHIO _ _GFP_FS GFP_KSWAPD _ _GFP_WAIT _ _GFP_IO _ _GFP_HIGHIO _ _GFP_FS GFP_USER _ _GFP_WAIT _ _GFP_IO _ _GFP_HIGHIO _ _GFP_FS GFP_HIGHUSER _ _GFP_WAIT _ _GFP_IO _ _GFP_HIGHIO _ _GFP_FS _ _GFP_HIGHMEM The _ _GFP_DMA and _ _GFP_HIGHMEM flags are called zone modifiers; they specify the zones searched by the kernel while looking for free page frames. The node_zonelists field of the contig_page_data node descriptor is an array of lists of zone descriptors; each list is associated with one specific combination of the zone modifiers. Although the array includes 16 elements, only 4 are really used, since there are currently only 2 zone modifiers. They are shown in Table 7-6. Table 7-6. Zone modifier lists _ _GFP_DMA _ _GFP_HIGHMEM Zone list 0 0 ZONE_NORMAL + ZONE_DMA 0 1 ZONE_HIGHMEM + ZONE_NORMAL + ZONE_DMA 1 0 ZONE_DMA 1 1 ZONE_DMA Page frames can be released through each of the following four functions and macros: _ _free_pages(page, order) This function checks the page descriptor pointed to by page; if the page frame is not reserved (i.e., if the PG_reserved flag is equal to 0), it decrements the count field of the descriptor. If count becomes 0, it assumes that 2order contiguous page frames starting from addr are no longer used. In this case, the function invokes _ _free_pages_ok( ) to insert the page frame descriptor of the first free page in the proper list of free page frames (described in the following section). free_pages(addr, order) This function is similar to _ _free_pages( ), but it receives as an argument the linear address addr of the first page frame to be released. _ _free_page(page) This macro releases the page frame having the descriptor pointed to by page; it expands to: _ _free_pages(page, 0) free_page(addr) This macro releases the page frame having the linear address addr; it expands to: free_pages(addr, 0) 7.1.6 Kernel Mappings of High-Memory Page Frames Page frames above the 896 MB boundary are not mapped in the fourth gigabyte of the kernel linear address spaces, so they cannot be directly accessed by the kernel. This implies that any page allocator function that returns the linear address of the assigned page frame doesn't work for the high memory. For instance, suppose that the kernel invoked _ _get_free_pages(GFP_HIGHMEM,0) to allocate a page frame in high memory. If the allocator assigned a page frame in high memory, _ _get_free_pages( ) cannot return its linear address because it doesn't exist; thus, the function returns NULL. In turn, the kernel cannot use the page frame; even worse, the page frame cannot be released because the kernel has lost track of it. In short, allocation of high-memory page frames must be done only through the alloc_pages( ) function and its alloc_page( ) shortcut, which both return the address of the page descriptor of the first allocated page frame. Once allocated, a high-memory page frame has to be mapped into the fourth gigabyte of the linear address space, even though the physical address of the page frame may well exceed 4 GB. To do this, the kernel may use three different mechanisms, which are called permanent kernel mappings, temporary kernel mappings, and noncontiguous memory allocation. In this section, we focus on the first two techniques; the third one is discussed in Section 7.3 later in this chapter. Establishing a permanent kernel mapping may block the current process; this happens when no free Page Table entries exist that can be used as "windows" on the page frames in high memory (see the next section). Thus, a permanent kernel mapping cannot be used in interrupt handlers and deferrable functions. Conversely, establishing a temporary kernel mapping never requires blocking the current process; its drawback, however, is that very few temporary kernel mappings can be established at the same time. Of course, none of these techniques allow addressing the whole RAM simultaneously. After all, only 128 MB of linear address space are left for mapping the high memory, while PAE supports systems having up to 64 GB of RAM. 7.1.6.1 Permanent kernel mappings Permanent kernel mappings allow the kernel to establish long-lasting mappings of high-memory page frames into the kernel address space. They use a dedicated Page Table whose address is stored in the pkmap_page_table variable. The number of entries in the Page Table is yielded by the LAST_PKMAP macro. As usual, the Page Table includes either 512 or 1,024 entries, according to whether PAE is enabled or disabled (see Section 2.4.6); thus, the kernel can access at most 2 or 4 MB of high memory at once. The Page Table maps the linear addresses starting from PKMAP_BASE (usually 0xfe000000). The address of the descriptor corresponding to the first page frame in high memory is stored in the highmem_start_page variable. The pkmap_count array includes LAST_PKMAP counters, one for each entry of the pkmap_page_table Page Table. We distinguish three cases: The counter is 0 The corresponding Page Table entry does not map any high-memory page frame and is usable. The counter is 1 The corresponding Page Table entry does not map any high-memory page frame, but it cannot be used because the corresponding TLB entry has not been flushed since its last usage. The counter is n (greater than 1) The corresponding Page Table entry maps a high-memory page frame, which is used by exactly n-1 kernel components. The kmap( ) function establishes a permanent kernel mapping. It is essentially equivalent to the following code: void * kmap(struct page * page) { if (page < highmem_page_start) return page->virtual; return kmap_high(page); } The virtual field of the page descriptor stores the linear address in the fourth gigabyte mapping the page frame, if any. Thus, for any page frame below the 896 MB boundary, the field always includes the physical address of the page frame plus PAGE_OFFSET. Conversely, if the page frame is in high memory, the virtual field has a non-null value only if the page frame is currently mapped, either by the permanent or the temporary kernel mapping. The kmap_high( ) function is invoked if the page frame really belongs to the high memory. The function is essentially equivalent to the following code: void * kmap_high(struct page * page) { unsigned long vaddr; spin_lock(&kmap_lock); vaddr = (unsigned long) page->virtual; if (!vaddr) vaddr = map_new_virtual(page); pkmap_count[(vaddr-PKMAP_BASE) >> PAGE_SHIFT]++; spin_unlock(&kmap_lock); return (void *) vaddr; } The function gets the kmap_lock spin lock to protect the Page Table against concurrent accesses in multiprocessor systems. Notice that there is no need to disable the interrupts because kmap( ) cannot be invoked by interrupt handlers and deferrable functions. Next, the kmap_high( ) function checks whether the virtual field of the page descriptor already stores a non-null linear address. If not, the function invokes the map_new_virtual( ) function to insert the page frame physical address in an entry of pkmap_page_table. Then kmap_high( ) increments the counter corresponding to the linear address of the page frame by 1 because another kernel component is going to access the page frame. Finally, kmap_high( ) releases the kmap_lock spin lock and returns the linear address that maps the page. The map_new_virtual( ) function essentially executes two nested loops: for (;;) { int count; DECLARE_WAITQUEUE(wait, current); for (count = LAST_PKMAP; count >= 0; --count) { last_pkmap_nr = (last_pkmap_nr + 1) & (LAST_PKMAP - 1); if (!last_pkmap_nr) { flush_all_zero_pkmaps( ); count = LAST_PKMAP; } if (!pkmap_count[last_pkmap_nr]) { unsigned long vaddr = PKMAP_BASE + (last_pkmap_nr << PAGE_SHIFT); set_pte(&(pkmap_page_table[last_pkmap_nr]), mk_pte(page, 0x63)); pkmap_count[last_pkmap_nr] = 1; page->virtual = (void *) vaddr; return vaddr; } } current->state = TASK_UNITERRUPTIBLE; add_wait_queue(&pkmap_map_wait, &wait); spin_unlock(&kmap_lock); schedule( ); remove_wait_queue(&pkmap_map_wait, &wait); spin_lock(&kmap_lock); if (page->virtual) return (unsigned long) page->virtual; } In the inner loop, the function scans all counters in pkmap_count that are looking for a null value. The last_pkmap_nr variable stores the index of the last used entry in the pkmap_page_table Page Table. Thus, the search starts from where it was left in the last invocation of the map_new_virtual( ) function. When the last counter in pkmap_count is reached, the search restarts from the counter at index 0. Before continuing, however, map_new_virtual( ) invokes the flush_all_zero_pkmaps( ) function, which starts another scanning of the counters looking for the value 1. Each counter that has value 1 denotes an entry in pkmap_page_table that is free but cannot be used because the corresponding TLB entry has not yet been flushed. flush_all_zero_pkmaps( ) issues the TLB flushes on such entries and resets their counters to zero. If the inner loop cannot find a null counter in pkmap_count, the map_new_virtual( ) function blocks the current process until some other process releases an entry of the pkmap_page_table Page Table. This is achieved by inserting current in the pkmap_map_wait wait queue, setting the current state to TASK_UNINTERRUPTIBLE and invoking schedule( ) to relinquish the CPU. Once the process is awoken, the function checks whether another process has mapped the page by looking at the virtual field of the page descriptor; if some other process has mapped the page, the inner loop is restarted. When a null counter is found by the inner loop, the map_new_virtual( ) function: 1. Computes the linear address that corresponds to the counter. 2. Writes the page's physical address into the entry in pkmap_page_table. The function also sets the bits Accessed, Dirty, Read/Write, and Present (value 0x63) in the same entry. 3. Sets to 1 the pkmap_count counter. 4. Writes the linear address into the virtual field of the page descriptor. 5. Returns the linear address. The kunmap( ) function destroys a permanent kernel mapping. If the page is really in the high memory zone, it invokes the kunmap_high( ) function, which is essentially equivalent to the following code: void kunmap_high(struct page * page) { spin_lock(&kmap_lock); if ((--pkmap_count[((unsigned long) page->virtual-PKMAP_BASE)>>PAGE_SHIFT])==1) wake_up(&pkmap_map_wait); spin_unlock(&kmap_lock); } Notice that if the counter of the Page Table entry becomes equal to 1 (free), kunmap_high( ) wakes up the processes waiting in the pkmap_map_wait wait queue. 7.1.6.2 Temporary kernel mappings Temporary kernel mappings are simpler to implement than permanent kernel mappings; moreover, they can be used inside interrupt handlers and deferrable functions because they never block the current process. Any page frame in high memory can be mapped through a window in the kernel address space—namely, a Page Table entry that is reserved for this purpose. The number of windows reserved for temporary kernel mappings is quite small. Each CPU has its own set of five windows whose linear addresses are identified by the enum km_type data structure: enum km_type { KM_BOUNCE_READ, KM_SKB_DATA, KM_SKB_DATA_SOFTIRQ, KM_USER0, KM_USER1, KM_TYPE_NR } The kernel must ensure that the same window is never used by two kernel control paths at the same time. Thus, each symbol is named after the kernel component that is allowed to use the corresponding window. The last symbol, KM_TYPE_NR, does not represent a linear address by itself, but yields the number of different windows usable by every CPU. Each symbol in km_type, except the last one, is an index of a fix-mapped linear address (see Section 2.5.6). The enum fixed_addresses data structure includes the symbols FIX_KMAP_BEGIN and FIX_KMAP_END; the latter is assigned to the index FIX_KMAP_BEGIN+(KM_TYPE_NR*NR_CPUS)-1. In this manner, there are KM_TYPE_NR fix-mapped linear addresses for each CPU in the system. Furthermore, the kernel initializes the kmap_pte variable with the address of the Page Table entry corresponding to the fix_to_virt(FIX_KMAP_BEGIN) linear address. To establish a temporary kernel mapping, the kernel invokes the kmap_atomic( ) function, which is essentially equivalent to the following code: void * kmap_atomic(struct page * page, enum km_type type) { enum fixed_addresses idx; if (page < highmem_start_page) return page->virtual; idx = type + KM_TYPE_NR * smp_processor_id( ); set_pte(kmap_pte-idx, mk_pte(page, 0x063)); _ _flush_tlb_one(fix_to_virt(FIX_KMAP_BEGIN+idx)); } The type argument and the CPU identifier specify what fix-mapped linear address has to be used to map the request page. The function returns the linear address of the page frame if it doesn't belong to high memory; otherwise, it sets up the Page Table entry corresponding to the fix-mapped linear address with the page's physical address and the bits Present, Accessed, Read/Write, and Dirty. Finally, the TLB entry corresponding to the linear address is flushed. To destroy a temporary kernel mapping, the kernel uses the kunmap_atomic( ) function. In the 80 x 86 architecture, however, this function does nothing. Temporary kernel mappings should be used carefully. A kernel control path using a temporary kernel mapping must never block, because another kernel control path might use the same window to map some other high memory page. 7.1.7 The Buddy System Algorithm The kernel must establish a robust and efficient strategy for allocating groups of contiguous page frames. In doing so, it must deal with a well-known memory management problem called external fragmentation: frequent requests and releases of groups of contiguous page frames of different sizes may lead to a situation in which several small blocks of free page frames are "scattered" inside blocks of allocated page frames. As a result, it may become impossible to allocate a large block of contiguous page frames, even if there are enough free pages to satisfy the request. There are essentially two ways to avoid external fragmentation: ● Use the paging circuitry to map groups of noncontiguous free page frames into intervals of contiguous linear addresses. ● Develop a suitable technique to keep track of the existing blocks of free contiguous page frames, avoiding as much as possible the need to split up a large free block to satisfy a request for a smaller one. The second approach is preferred by the kernel for three good reasons: ● In some cases, contiguous page frames are really necessary, since contiguous linear addresses are not sufficient to satisfy the request. A typical example is a memory request for buffers to be assigned to a DMA processor (see Chapter 13). Since the DMA ignores the paging circuitry and accesses the address bus directly while transferring several disk sectors in a single I/O operation, the buffers requested must be located in contiguous page frames. ● Even if contiguous page frame allocation is not strictly necessary, it offers the big advantage of leaving the kernel paging tables unchanged. What's wrong with modifying the Page Tables? As we know from Chapter 2, frequent Page Table modifications lead to higher average memory access times, since they make the CPU flush the contents of the translation lookaside buffers. ● Large chunks of contiguous physical memory can be accessed by the kernel through 4 MB pages. The reduction of translation lookaside buffers misses, in comparison to the use of 4 KB pages, significantly speeds up the average memory access time (see Section 2.4.8). The technique adopted by Linux to solve the external fragmentation problem is based on the well-known buddy system algorithm. All free page frames are grouped into 10 lists of blocks that contain groups of 1, 2, 4, 8, 16, 32, 64, 128, 256, and 512 contiguous page frames, respectively. The physical address of the first page frame of a block is a multiple of the group size—for example, the initial address of a 16-page- frame block is a multiple of 16 x 212 (212 = 4,096, which is the regular page size). We'll show how the algorithm works through a simple example. Assume there is a request for a group of 128 contiguous page frames (i.e., a half-megabyte). The algorithm checks first to see whether a free block in the 128-page-frame list exists. If there is no such block, the algorithm looks for the next larger block—a free block in the 256-page-frame list. If such a block exists, the kernel allocates 128 of the 256 page frames to satisfy the request and inserts the remaining 128 page frames into the list of free 128-page-frame blocks. If there is no free 256-page block, the kernel then looks for the next larger block (i.e., a free 512-page-frame block). If such a block exists, it allocates 128 of the 512 page frames to satisfy the request, inserts the first 256 of the remaining 384 page frames into the list of free 256-page-frame blocks, and inserts the last 128 of the remaining 384 page frames into the list of free 128-page-frame blocks. If the list of 512-page-frame blocks is empty, the algorithm gives up and signals an error condition. The reverse operation, releasing blocks of page frames, gives rise to the name of this algorithm. The kernel attempts to merge pairs of free buddy blocks of size b together into a single block of size 2b. Two blocks are considered buddies if: ● Both blocks have the same size, say b. ● They are located in contiguous physical addresses. ● The physical address of the first page frame of the first block is a multiple of 2 x b x 212. The algorithm is iterative; if it succeeds in merging released blocks, it doubles b and tries again so as to create even bigger blocks. 7.1.7.1 Data structures Linux uses a different buddy system for each zone. Thus, in the 80 x 86 architecture, there are three buddy systems: the first handles the page frames suitable for ISA DMA, the second handles the "normal" page frames, and the third handles the high-memory page frames. Each buddy system relies on the following main data structures: ● The mem_map array introduced previously. Actually, each zone is concerned with a subset of the mem_map elements. The first element in the subset and its number of elements are specified, respectively, by the zone_mem_map and size fields of the zone descriptor. ● An array having 10 elements of type free_area_t, one element for each group size. The array is stored in the free_area field of the zone descriptor. ● Ten binary arrays named bitmaps, one for each group size. Each buddy system has its own set of bitmaps, which it uses to keep track of the blocks it allocates. The free_area_t (or equivalently, struct free_area_struct) data structure is defined as follows: typedef struct free_area_struct { struct list_head free_list; unsigned long *map; } free_area_t; The k th element of the free_area array in the zone descriptor is associated with a doubly linked circular list of blocks of size 2k; each member of such a list is the descriptor of the first page frame of a block. The list is implemented through the list field of the page descriptor. The map field points to a bitmap whose size depends on the number of page frames in the zone. Each bit of the bitmap of the k th entry of the free_area array describes the status of two buddy blocks of size 2k page frames. If a bit of the bitmap is equal to 0, either both buddy blocks of the pair are free or both are busy; if it is equal to 1, exactly one of the blocks is busy. When both buddies are free, the kernel treats them as a single free block of size 2k+1. Let's consider, for sake of illustration, a zone including 128 MB of RAM. The 128 MB can be divided into 32,768 single pages, 16,384 groups of 2 pages each, or 8,192 groups of 4 pages each, and so on up to 64 groups of 512 pages each. So the bitmap corresponding to free_area[0] consists of 16,384 bits, one for each pair of the 32,768 existing page frames; the bitmap corresponding to free_area[1] consists of 8,192 bits, one for each pair of blocks of two consecutive page frames; the last bitmap corresponding to free_area[9] consists of 32 bits, one for each pair of blocks of 512 contiguous page frames. Figure 7-2 illustrates the use of the data structures introduced by the buddy system algorithm. The array zone_mem_map contains nine free page frames grouped in one block of one (a single page frame) at the top and two blocks of four further down. The double arrows denote doubly linked circular lists implemented by the free_list field. Notice that the bitmaps are not drawn to scale. Figure 7-2. Data structures used by the buddy system 7.1.7.2 Allocating a block The alloc_pages( ) function is the core of the buddy system allocation algorithm. Any other allocator function or macro listed in the earlier section Section 7.1.5 ends up invoking alloc_pages( ). The function considers the list of the contig_page_data.node_zonelists array corresponding to the zone modifiers specified in the argument gfp_mask. Starting with the first zone descriptor in the list, it compares the number of free page frames in the zone (stored in the free_pages field of the zone descriptor), the number of requested page frames (argument order of alloc_pages( )), and the threshold value stored in the pages_low field of the zone descriptor. If free_pages - 2 order is smaller than or equal to pages_low, the function skips the zone and considers the next zone in the list. If no zone has enough free page frames, alloc_pages( ) restarts the loop, this time looking for a zone that has at least pages_min free page frames. If such a zone doesn't exist and if the current process is allowed to wait, the function invokes balance_classzone( ), which in turn invokes try_to_free_pages( ) to reclaim enough page frames to satisfy the memory request (see Section 16.7). When alloc_pages( ) finds a zone with a suitable number of free page frames, it invokes the rmqueue( ) function to allocate a block in that zone. The function takes two arguments: the address of the zone descriptor, and order, which denotes the logarithm of the size of the requested block of free pages (0 for a one-page block, 1 for a two-page block, and so forth). If the page frames are successfully allocated, the rmqueue( ) function returns the address of the page descriptor of the first allocated page frame; that address is also returned by alloc_pages( ). Otherwise, rmqueue( ) returns NULL, and alloc_pages( ) consider the next zone in the list. The rmqueue( ) function is equivalent to the following fragments. First, a few local variables are declared and initialized: free_area_t * area = &(zone->free_area[order]); unsigned int curr_order = order; struct list_head *head, *curr; struct page *page; unsigned long flags; unsigned int index; unsigned long size; The function disables interrupts and acquires the spin lock of the zone descriptor because it will alter its fields to allocate a block. Then it performs a cyclic search through each list for an available block (denoted by an entry that doesn't point to the entry itself), starting with the list for the requested order and continuing if necessary to larger orders. This is equivalent to the following fragment: spin_lock_irqsave(&zone->lock, flags); do { head = &area->free_list; curr = head->next; if (curr != head) goto block_found; curr_order++; area++; } while (curr_order < 10); spin_unlock_irqrestore(&zone->lock, flags); return NULL; If the loop terminates, no suitable free block has been found, so rmqueue( ) returns a NULL value. Otherwise, a suitable free block has been found; in this case, the descriptor of its first page frame is removed from the list, the corresponding bitmap is updated, and the value of free_ pages in the zone descriptor is decreased: block_found: page = list_entry(curr, struct page, list); list_del(curr); index = page - zone->zone_mem_map; if (curr_order != 9) change_bit(index>>(1+curr_order), area->map); zone->free_pages -= 1UL << order; If the block found comes from a list of size curr_order greater than the requested size order, a while cycle is executed. The rationale behind these lines of codes is as follows: when it becomes necessary to use a block of 2k page frames to satisfy a request for 2h page frames (h < k), the program allocates the last 2h page frames and iteratively reassigns the first 2k - 2h page frames to the free_area lists that have indexes between h and k: size = 1 << curr_order; while (curr_order > order) { area--; curr_order--; size >>= 1; /* insert *page as first element in the list and update the bitmap */ list_add(&page->list, &area->free_list); change_bit(index >> (1+curr_order), area->map); /* now take care of the second half of the free block starting at *page */ index += size; page += size; } Finally, rmqueue( ) releases the spin lock, updates the count field of the page descriptor associated with the selected block, and executes the return instruction: spin_unlock_irqrestore(&zone->lock, flags); atomic_set(&page->count, 1); return page; As a result, the alloc_pages( ) function returns the address of the page descriptor of the first page frame allocated. 7.1.7.3 Freeing a block The _ _free_pages_ok( ) function implements the buddy system strategy for freeing page frames. It uses two input parameters: page The address of the descriptor of the first page frame included in the block to be released order The logarithmic size of the block The _ _free_pages_ok( ) function usually inserts the block of page frames in the buddy system data structures so they can be used in subsequent allocation requests. One case is an exception: if the current process is moving pages across memory zones to rebalance them, the function does not free the page frames, but inserts the block in a special list of the process. To decide what to do with the block of page frames, _ _free_pages_ok( ) checks the PF_FREE_PAGES flag of the process. It is set only if the process is rebalancing the memory zones. Anyway, we discuss this special case in Chapter 16; we assume here that the PF_FREE_PAGES flag of current is not set, so _ _free_pages_ok( ) inserts the block in the buddy system data structures. The function starts by declaring and initializing a few local variables: unsigned long flags; unsigned long mask = (~0UL) << order; zone_t * zone = page->zone; struct page * base = zone->zone_mem_map; free_area_t * area = &zone->free_area[order]; unsigned long page_idx = page - base; unsigned long index = page_idx >> (1 + order); struct page * buddy; The page_idx local variable contains the index of the first page frame in the block with respect to the first page frame of the zone. The index local variable contains the bit number corresponding to the block in the bitmap. The function clears the PG_referenced and PG_dirty flags of the first page frame, then it acquires the zone spin lock and disables interrupts: page->flags &= ~((1<lock, flags); The mask local variable contains the two's complement of 2order. It is used to increment the counter of free page frames in the zone: zone->free_pages -= mask; The function now starts a cycle executed at most 9 - order times, once for each possibility for merging a block with its buddy. The function starts with the smallest-sized block and moves up to the top size. The condition driving the while loop is: mask + (1 << 9) In the body of the loop, the bits set in mask are shifted to the left at each iteration and the buddy block of the block that has the number page_idx is checked: if (!test_and_change_bit(index, area->map)) break; If the buddy block is not free, the function breaks out of the cycle; if it is free, the function detaches it from the corresponding list of free blocks. The block number of the buddy is derived from page_idx by switching a single bit: buddy = &base[page_idx ^ -mask]; list_del(&buddy->list); At the end of each iteration, the function updates the mask, area, index, and page_idx local variables: mask <<= 1; area++; index >>= 1; page_idx &= mask; The function then continues the next iteration, trying to merge free blocks twice as large as the ones considered in the previous cycle. When the cycle is finished, the free block obtained cannot be merged further with other free blocks. It is then inserted in the proper list: list_add(&(base[page_idx].list), &area->free_list); Finally, the function releases the zone spin lock and returns: spin_unlock_irqrestore(&zone->lock, flags); return; I l@ve RuBoard I l@ve RuBoard 7.2 Memory Area Management This section deals with memory areas—that is, with sequences of memory cells having contiguous physical addresses and an arbitrary length. The buddy system algorithm adopts the page frame as the basic memory area. This is fine for dealing with relatively large memory requests, but how are we going to deal with requests for small memory areas, say a few tens or hundreds of bytes? Clearly, it would be quite wasteful to allocate a full page frame to store a few bytes. A better approach instead consists of introducing new data structures that describe how small memory areas are allocated within the same page frame. In doing so, we introduce a new problem called internal fragmentation. It is caused by a mismatch between the size of the memory request and the size of the memory area allocated to satisfy the request. A classical solution (adopted by early Linux versions) consists of providing memory areas whose sizes are geometrically distributed; in other words, the size depends on a power of 2 rather than on the size of the data to be stored. In this way, no matter what the memory request size is, we can ensure that the internal fragmentation is always smaller than 50 percent. Following this approach, the kernel creates 13 geometrically distributed lists of free memory areas whose sizes range from 32 to 131, 056 bytes. The buddy system is invoked both to obtain additional page frames needed to store new memory areas and, conversely, to release page frames that no longer contain memory areas. A dynamic list is used to keep track of the free memory areas contained in each page frame. 7.2.1 The Slab Allocator Running a memory area allocation algorithm on top of the buddy algorithm is not particularly efficient. A better algorithm is derived from the slab allocator schema developed in 1994 for the Sun Microsystem Solaris 2.4 operating system. It is based on the following premises: ● The type of data to be stored may affect how memory areas are allocated; for instance, when allocating a page frame to a User Mode process, the kernel invokes the get_zeroed_page( ) function, which fills the page with zeros. The concept of a slab allocator expands upon this idea and views the memory areas as objects consisting of both a set of data structures and a couple of functions or methods called the constructor and destructor . The former initializes the memory area while the latter deinitializes it. To avoid initializing objects repeatedly, the slab allocator does not discard the objects that have been allocated and then released but instead saves them in memory. When a new object is then requested, it can be taken from memory without having to be reinitialized. In practice, the memory areas handled by Linux do not need to be initialized or deinitialized. For efficiency reasons, Linux does not rely on objects that need constructor or destructor methods; the main motivation for introducing a slab allocator is to reduce the number of calls to the buddy system allocator. Thus, although the kernel fully supports the constructor and destructor methods, the pointers to these methods are NULL. ● The kernel functions tend to request memory areas of the same type repeatedly. For instance, whenever the kernel creates a new process, it allocates memory areas for some fixed size tables such as the process descriptor, the open file object, and so on (see Chapter 3). When a process terminates, the memory areas used to contain these tables can be reused. Since processes are created and destroyed quite frequently, without the slab allocator, the kernel wastes time allocating and deallocating the page frames containing the same memory areas repeatedly; the slab allocator allows them to be saved in a cache and reused quickly. ● Requests for memory areas can be classified according to their frequency. Requests of a particular size that are expected to occur frequently can be handled most efficiently by creating a set of special-purpose objects that have the right size, thus avoiding internal fragmentation. Meanwhile, sizes that are rarely encountered can be handled through an allocation scheme based on objects in a series of geometrically distributed sizes (such as the power-of-2 sizes used in early Linux versions), even if this approach leads to internal fragmentation. ● There is another subtle bonus in introducing objects whose sizes are not geometrically distributed: the initial addresses of the data structures are less prone to be concentrated on physical addresses whose values are a power of 2. This, in turn, leads to better performance by the processor hardware cache. ● Hardware cache performance creates an additional reason for limiting calls to the buddy system allocator as much as possible. Every call to a buddy system function "dirties" the hardware cache, thus increasing the average memory access time. The impact of a kernel function on the hardware cache is called the function footprint; it is defined as the percentage of cache overwritten by the function when it terminates. Clearly, large footprints lead to a slower execution of the code executed right after the kernel function, since the hardware cache is by now filled with useless information. The slab allocator groups objects into caches. Each cache is a "store" of objects of the same type. For instance, when a file is opened, the memory area needed to store the corresponding "open file" object is taken from a slab allocator cache named filp (for "file pointer"). The slab allocator caches used by Linux may be viewed at runtime by reading the /proc/slabinfo file. The area of main memory that contains a cache is divided into slabs; each slab consists of one or more contiguous page frames that contain both allocated and free objects (see Figure 7-3). Figure 7-3. The slab allocator components The slab allocator never releases the page frames of an empty slab on its own. It would not know when free memory is needed, and there is no benefit to releasing objects when there is still plenty of free memory for new objects. Therefore, releases occur only when the kernel is looking for additional free page frames (see Section 7.2.13 later in this chapter and Section 16.7). 7.2.2 Cache Descriptor Each cache is described by a table of type struct kmem_cache_s (which is equivalent to the type kmem_cache_t). The most significant fields of this table are: name Character array storing the name of the cache. slabs_full Doubly linked circular list of slab descriptors with no free objects. slabs_partial Doubly linked circular list of slab descriptors with both free and nonfree objects. slabs_free Doubly linked circular list of slab descriptors with free objects only. spinlock Spin lock protecting the cache from concurrent accesses in multiprocessor systems. num Number of objects packed into a single slab. (All slabs of the cache have the same size.) objsize Size of the objects included in the cache. (This size may be rounded up by the slab allocator if the initial addresses of the objects must be memory-aligned.) gfporder Logarithm of the number of contiguous page frames included in a single slab. ctor, dtor Point, respectively, to the constructor and destructor methods associated with the cache objects. They are currently set to NULL, as stated earlier. next Pointers for the doubly linked list of cache descriptors. flags A set of flags that describes permanent properties of the cache. There is, for instance, a flag that specifies which of two possible alternatives (see the following section) has been chosen to store the object descriptors in memory. dflags A set of flags that describe dynamic properties of the cache. There is, for instance, a flag that indicates whether the kernel is allocating new slabs to the cache. In multiprocessor systems, they must be accessed by acquiring the cache spin lock. gfpflags A set of flags passed to the buddy system function when allocating page frames. The field is typically used to specify the _ _GFP_DMA and _ _GFP_HIGHMEM zone modifiers. For instance, if _ _GFP_DMA is set in gfpflags, all objects of the cache can be used for ISA DMA. 7.2.3 Slab Descriptor Each slab of a cache has its own descriptor of type struct slab_s (equivalent to the type slab_t). Slab descriptors can be stored in two possible places: External slab descriptor Stored outside the slab, in one of the general caches not suitable for ISA DMA pointed to by cache_sizes. Internal slab descriptor Stored inside the slab, at the beginning of the first page frame assigned to the slab. The slab allocator chooses the second solution when the size of the objects is smaller than 512 or when internal fragmentation leaves enough space for the slab—and object descriptors (as described later)—inside the slab. The most significant fields of a slab descriptor are: inuse Number of objects in the slab that are currently allocated. s_mem Points to the first object (either allocated or free) inside the slab. free Points to the first free object (if any) in the slab. list Pointers for one of the three doubly linked lists of slab descriptors (either the slabs_full, slabs_partial, or slabs_free list in the cache descriptor). Figure 7-4 illustrates the major relationships between cache and slab descriptors. Full slabs, partially full slabs, and free slabs are linked in different lists. Figure 7-4. Relationship between cache and slab descriptors 7.2.4 General and Specific Caches Caches are divided into two types: general and specific. General caches are used only by the slab allocator for its own purposes, while specific caches are used by the remaining parts of the kernel. The general caches are: ● A first cache contains the cache descriptors of the remaining caches used by the kernel. The cache_cache variable contains its descriptor. ● Twenty-six additional caches contain geometrically distributed memory areas. The table, called cache_sizes (whose elements are of type cache_sizes_t), points to the 26 cache descriptors associated with memory areas of size 32, 64, 128, 256, 512, 1,024, 2,048, 4,096, 8,192, 16,384, 32,768, 65,536, and 131,072 bytes, respectively. For each size, there are two caches: one suitable for ISA DMA allocations and the other for normal allocations. The table cache_sizes is used to efficiently derive the cache address corresponding to a given size. The kmem_cache_init( ) and kmem_cache_sizes_init( ) functions are invoked during system initialization to set up the general caches. Specific caches are created by the kmem_cache_create( ) function. Depending on the parameters, the function first determines the best way to handle the new cache (for instance, whether to include the slab descriptor inside or outside of the slab). It then creates a new cache descriptor for the new cache and inserts the descriptor in the cache_cache general cache. It is also possible to destroy a cache by invoking kmem_cache_destroy( ). This function is mostly useful to modules that create their own caches when loaded and destroy them when unloaded. To avoid wasting memory space, the kernel must destroy all slabs before destroying the cache itself. The kmem_cache_shrink( ) function destroys all the slabs in a cache by invoking kmem_slab_destroy( ) iteratively (see the later section Section 7.2.7). The growing field of the cache descriptor is used to prevent kmem_cache_shrink( ) from shrinking a cache while another kernel control path attempts to allocate a new slab for it. The names of all general and specific caches can be obtained at runtime by reading /proc/slabinfo; this file also specifies the number of free objects and the number of allocated objects in each cache. 7.2.5 Interfacing the Slab Allocator with the Buddy System When the slab allocator creates new slabs, it relies on the buddy system algorithm to obtain a group of free contiguous page frames. For this purpose, it invokes the kmem_getpages( ) function: void * kmem_getpages(kmem_cache_t *cachep, unsigned long flags) { void *addr; flags |= cachep->gfpflags; addr = (void*) _ _get_free_pages(flags, cachep->gfporder); return addr; } The parameters have the following meaning: cachep Points to the cache descriptor of the cache that needs additional page frames (the number of required page frames is determined by the order in the cachep->gfporder field) flags Specifies how the page frame is requested (see Section 7.1.5 earlier in this chapter). This set of flags is combined with the specific cache allocation flags stored in the gfpflags of the cache descriptor. In the reverse operation, page frames assigned to a slab allocator can be released (see Section 7.2.7 later in this chapter) by invoking the kmem_freepages( ) function: void kmem_freepages(kmem_cache_t *cachep, void *addr) { unsigned long i = (1<gfporder); struct page *page = & mem_map[_ _pa(addr) >> PAGE_SHIFT]; while (i--) { PageClearSlab(page); page++; } free_pages((unsigned long) addr, cachep->gfporder); } The function releases the page frames, starting from the one having the linear address addr, that had been allocated to the slab of the cache identified by cachep. 7.2.6 Allocating a Slab to a Cache A newly created cache does not contain slab and therefore does not contain any free objects. New slabs are assigned to a cache only when both of the following are true: ● A request has been issued to allocate a new object. ● The cache does not include free object. Under these circumstances, the slab allocator assigns a new slab to the cache by invoking kmem_cache_grow( ). This function calls kmem_ getpages( ) to obtain a group of page frames from the buddy system; it then calls kmem_cache_slabmgmt( ) to get a new slab descriptor, either in the first page frame of the slab or in the general cache of order 0 pointed to by cache_sizes. Next, it calls kmem_cache_init_objs( ), which applies the constructor method (if defined) to all the objects contained in the new slab. Then, kmem_cache_ grow( ) scans all page descriptors of the page frames assigned to the new slab, and loads the next and prev subfields of the list fields in the page descriptors with the addresses of, respectively, the cache descriptor and the slab descriptor. This works correctly because the list field is used by functions of the buddy system only when the page frame is free, while page frames handled by the slab allocator functions are not free as far as the buddy system is concerned. Therefore, the buddy system is not confused by this specialized use of the page frame descriptor. The function also sets the PG_slab flag of the page frames. The function then adds the slab descriptor *slabp at the end of the fully free slab list of the cache descriptor *cachep: list_add_tail(&slabp->list, &cachep->slabs_free); 7.2.7 Releasing a Slab from a Cache As stated previously, the slab allocator never releases the page frames of an empty slab on its own. In fact, a slab is released only if both of the following conditions are true: ● The buddy system is unable to satisfy a new request for a group of page frames (a zone is low on memory). ● The slab is empty—all the objects included in it are unused. When the kernel looks for additional free page frames, it calls try_to_free_pages( ); this function, in turn, may invoke kmem_cache_reap( ), which selects a cache that contains at least one empty slab. The function then removes the slab from the fully free slab list and destroys it by invoking kmem_slab_destroy( ): void kmem_slab_destroy(kmem_cache_t *cachep, slab_t *slabp) { if (cachep->dtor) { int i; for (i = 0; i < cachep->num; i++) { void* objp = & slabp->s_mem[cachep->objsize*i]; (cachep->dtor)(objp, cachep, 0); } } kmem_freepages(cachep, slabp->s_mem - slabp->colouroff); if (OFF_SLAB(cachep)) kmem_cache_free(cachep->slabp_cache, slabp); } The function checks whether the cache has a destructor method for its objects (the dtor field is not NULL), in which case it applies the destructor to all the objects in the slab; the objp local variable keeps track of the currently examined object. Next, it calls kmem_freepages( ), which returns all the contiguous page frames used by the slab to the buddy system. Finally, if the slab descriptor is stored outside of the slab (macro OFF_SLAB returns true, as explained later in this chapter), the function releases it from the cache of slab descriptors. 7.2.8 Object Descriptor Each object has a descriptor of type kmem_bufctl_t. Object descriptors are stored in an array placed after the corresponding slab descriptor. Thus, like the slab descriptors themselves, the object descriptors of a slab can be stored in two possible ways that are illustrated in Figure 7-5. Figure 7-5. Relationships between slab and object descriptors External object descriptors Stored outside the slab, in one of the general caches pointed to by cache_sizes. The size of the memory area, and thus the particular general cache used to store object descriptors, depends on the number of objects stored in the slab (num field of the cache descriptor). Internal object descriptors Stored inside the slab, right after the objects they describe. The first object descriptor in the array describes the first object in the slab, and so on. An object descriptor is simply a unsigned integer, which is meaningful only when the object is free. It contains the index of the next free object in the slab, thus implementing a simple list of free objects inside the slab. The object descriptor of the last element in the free object list is marked by the conventional value BUFCTL_END (0xffffffff). 7.2.9 Aligning Objects in Memory The objects managed by the slab allocator are aligned in memory—that is, they are stored in memory cells whose initial physical addresses are multiples of a given constant, which is usually a power of 2. This constant is called the alignment factor. The largest alignment factor allowed by the slab allocator is 4,096—the page frame size. This means that objects can be aligned by referring to either their physical addresses or their linear addresses. In both cases, only the 12 least significant bits of the address may be altered by the alignment. Usually, microcomputers access memory cells more quickly if their physical addresses are aligned with respect to the word size (that is, to the width of the internal memory bus of the computer). Thus, by default, the kmem_cache_create( ) function aligns objects according to the word size specified by the BYTES_PER_WORD macro. For Intel Pentium processors, the macro yields the value 4 because the word is 32 bits long. When creating a new slab cache, it's possible to specify that the objects included in it be aligned in the first-level hardware cache. To achieve this, set the SLAB_HWCACHE_ALIGN cache descriptor flag. The kmem_cache_create( ) function handles the request as follows: ● If the object's size is greater than half of a cache line, it is aligned in RAM to a multiple of L1_CACHE_BYTES—that is, at the beginning of the line. ● Otherwise, the object size is rounded up to a factor of L1_CACHE_BYTES; this ensures that an object will never span across two cache lines. Clearly, what the slab allocator is doing here is trading memory space for access time; it gets better cache performance by artificially increasing the object size, thus causing additional internal fragmentation. 7.2.10 Slab Coloring We know from Chapter 2 that the same hardware cache line maps many different blocks of RAM. In this chapter, we have also seen that objects of the same size tend to be stored at the same offset within a cache. Objects that have the same offset within different slabs will, with a relatively high probability, end up mapped in the same cache line. The cache hardware might therefore waste memory cycles transferring two objects from the same cache line back and forth to different RAM locations, while other cache lines go underutilized. The slab allocator tries to reduce this unpleasant cache behavior by a policy called slab coloring: different arbitrary values called colors are assigned to the slabs. Before examining slab coloring, we have to look at the layout of objects in the cache. Let's consider a cache whose objects are aligned in RAM. This means that the object address must be a multiple of a given positive value, say aln. Even taking the alignment constraint into account, there are many possible ways to place objects inside the slab. The choices depend on decisions made for the following variables: num Number of objects that can be stored in a slab (its value is in the num field of the cache descriptor). osize Object size, including the alignment bytes. dsize Slab descriptor size plus all object descriptors size. Its value is equal to 0 if the slab and object descriptors are stored outside of the slab. free Number of unused bytes (bytes not assigned to any object) inside the slab. The total length in bytes of a slab can then be expressed as: slab length = (num x osize) + dsize + free free is always smaller than osize, since otherwise, it would be possible to place additional objects inside the slab. However, free could be greater than aln. The slab allocator takes advantage of the free unused bytes to color the slab. The term "color" is used simply to subdivide the slabs and allow the memory allocator to spread objects out among different linear addresses. In this way, the kernel obtains the best possible performance from the microprocessor's hardware cache. Slabs having different colors store the first object of the slab in different memory locations, while satisfying the alignment constraint. The number of available colors is (free/aln)+1. The first color is denoted as 0 and the last one (whose value is in the colour field of the cache descriptor) is denoted as free/aln. If a slab is colored with color col, the offset of the first object (with respect to the slab initial address) is equal to col x aln+dsize bytes; this value is stored in the colour_off field of the cache descriptor. Figure 7-6 illustrates how the placement of objects inside the slab depends on the slab color. Coloring essentially leads to moving some of the free area of the slab from the end to the beginning. Figure 7-6. Slab with color col and alignment aln Coloring works only when free is large enough. Clearly, if no alignment is required for the objects or if the number of unused bytes inside the slab is smaller than the required alignment (free < aln), the only possible slab coloring is the one that has the color 0—the one that assigns a zero offset to the first object. The various colors are distributed equally among slabs of a given object type by storing the current color in a field of the cache descriptor called colour_next. The kmem_cache_ grow( ) function assigns the color specified by colour_next to a new slab and then increments the value of this field. After reaching colour, it wraps around again to 0. In this way, each slab is created with a different color from the previous one, up to the maximum available colors. 7.2.11 Local Array of Objects in Multiprocessor Systems The Linux 2.4 implementation of the slab allocator for multiprocessor systems differs from that of the original Solaris 2.4. To reduce spin lock contention among the processors, each cache of the slab allocator includes a small array of pointers to freed objects for each CPU in the system. Most of allocations and releases of slab objects affect the local array only; the slab data structures get involved only when the local array underflows or overflows. The cache descriptor includes a cpudata array of pointers to cpucache_t data structures, one element for each CPU in the system. The cpucache_t data structure represents the descriptor of the local array of objects and includes the following fields: avail The number of available objects in the local array. It also acts as the index of the first free slot in the array. limit The size of the local array—that is, the maximum number of objects in the local array. Notice that the local array descriptor does not include the address of the array itself; in fact, it is placed right after the descriptor. Of course, the array stores the pointers to the freed objects, not the object themselves, which are always placed inside the slabs of the cache. Nevertheless, the default size of the array depends on the size of the objects stored in the slab cache: the array size for small objects (up to 255 bytes) is 252 elements, the size for medium-size objects (between 256 and 1,023 bytes) is 124 elements, and the size for large objects (greater than 1,023 bytes) is 60 elements. Anyway, the system administrator can tune the size of the arrays for each cache by writing into the /proc/slabinfo file. 7.2.12 Allocating an Object in a Cache New objects may be obtained by invoking the kmem_cache_alloc( ) function. The parameter cachep points to the cache descriptor from which the new free object must be obtained, while the parameter flag represents the flags to be passed to the buddy system allocator functions, should all slabs of the cache be full. The function differs for uniprocessor systems and multiprocessor ones because in the latter case, it must also cope with the local array of freed objects. Let's discuss these two cases separately. 7.2.12.1 The uniprocessor case kmem_cache_alloc( ) first disables the local interrupts; it then looks for a slab that includes a free object: void * objp; slab_t * slabp; struct list_head * entry; local_irq_save(save_flags); entry = cachep->slabs_partial.next; if (entry == & cachep->slabs_partial) { entry = cachep->slabs_free.next; if (entry == & cachep->slabs_free) goto alloc_new_slab; list_del(entry); list_add(entry, & cachep->slab_partials); } slabp = list_entry(entry, slab_t, list); The function looks into the slabs_partial doubly linked list, which links the descriptors of the slab that has at least one free object. If the list is empty (the list head points to itself), the function moves the first slab descriptor in the slabs_free list into slabs_partial. If even slabs_free is empty, the function allocates a new slab to the cache by invoking kmem_cache_grow( ), and then the whole procedure is repeated. After obtaining a slab with a free object, the function increments the counter containing the number of objects currently allocated in the slab: slabp->inuse++; It then loads the objp local variable with the address of the first free object inside the slab: objp = & slabp->s_mem[slabp->free * cachep->objsize]; The kmem_cache_alloc( ) function then updates the slabp->free field of the slab descriptor to point to the next free object: slabp->free = ((kmem_bufctl_*)(slabp+1))[slabp->free]; if (slabp->free == BUFCTL_END) { list_del(&slabp->list); list_add(&slabp->list, &cachep->slabs_full); } Recall that the object descriptor of a free object stores either the index of another free object in the slab, or it stores BUFCTL_END if the free object is the last one. The array of object descriptors is placed right after the slab descriptor, so its address is computed as (slabp+1). The function terminates by re-enabling the local interrupts and returning the address of the new object: local_irq_restore(save_flags); return objp; 7.2.12.2 The multiprocessor case kmem_cache_alloc( ) first disables the local interrupts; it then looks for a free object in the cache's local array associated with the running CPU: void * objp; cpucache_t * cc; local_irq_save(save_flags); cc = cachep->cpudata[smp_processor_id( )]; if (cc->avail) objp = ((void *)(cc+1))[--cc->avail]; else { objp = kmem_cache_alloc_batch(cachep, flags); if (!objp) goto alloc_new_slab; } local_irq_restore(save_flags); return objp; The cc local variable contains the address of the local array descriptor; thus, (cc+1) yields the address of the first local array element. If the avail field of the local array descriptor is positive, the function loads the address of the corresponding object into the objp local variable and decrements the counter. Otherwise, it invokes kmem_cache_alloc_batch( ) to repopulate the local array. The kmem_cache_alloc_batch( ) function gets the cache spin lock and then allocates a predefined number of objects from the cache and inserts them into the local array: count = cachep->batchcount; cc = cachep->cpudata[smp_processor_id( )]; spin_lock(&cachep->spinlock); while (count--) { entry = cachep->slabs_partial.next; if (entry == &cachep->slabs_partial) { entry = cachep->slabs_free.next; if (entry == slabs_free) break; list_del(entry); list_add(entry, &cachep->slabs_partial); } slabp = list_entry(entry, slab_t, list); slabp->inuse++; objp = & slabp->s_mem[slabp->free * cachep->objsize]; slabp->free = ((kmem_bufctl_*)(((slab_t *)slabp)+1))[slabp->free]; if (slabp->free == BUFCTL_END) { list_del(&slabp->list); list_add(&slabp->list, &cachep->slabs_full); } ((void *)(cc+1))[cc->avail++] = objp; } spin_unlock(&cachep->spinlock); if (cc->avail) return ((void *)(cc+1))[--cc->avail]; return NULL; The number of pre-allocated objects is stored in the batchcount field of the cache descriptor; by default, it is half of the local array size, but the system administrator can modify it by writing into the /proc/slabinfo file. The code that gets the objects from the slabs is identical to that of the uniprocessor case, so we won't discuss it further. The kmem_cache_alloc_batch( ) function returns NULL if the cache does not have free objects. In this case, kmem_cache_alloc( ) invokes kmem_cache_grow( ) and then repeats the whole procedure, (as in the uniprocessor case). 7.2.13 Releasing an Object from a Cache The kmem_cache_free( ) function releases an object previously obtained by the slab allocator. Its parameters are cachep (the address of the cache descriptor) and objp (the address of the object to be released). As with kmem_cache_alloc( ), we discuss the uniprocessor case separately from the multiprocessor case. 7.2.13.1 The uniprocessor case The function starts by disabling the local interrupts and then determines the address of the descriptor of the slab containing the object. It uses the list.prev subfield of the descriptor of the page frame storing the object: slab_t * slabp; unsigned int objnr; local_irq_save(save_flags); slabp = (slab_t *) mem_map[_ _pa(objp) >> PAGE_SHIFT].list.prev; Then the function computes the index of the object inside its slab, derives the address of its object descriptor, and adds the object to the head of the slab's list of free objects: objnr = (objp - slabp->s_mem) / cachep->objsize; ((kmem_bufctl_t *)(slabp+1))[objnr] = slabp->free; slabp->free = objnr; Finally, the function checks whether the slab has to be moved to another list: if (--slabp->inuse == 0) { /* slab is now fully free */ list_del(&slabp->list); list_add(&slabp->list, &cachep->slabs_free); } else if (slabp->inuse+1 == cachep->num) { /* slab was full */ list_del(&slabp->list); list_add(&slabp->list, &cachep->slabs_partial); } local_irq_restore(save_flags); return; 7.2.13.2 The multiprocessor case The function starts by disabling the local interrupts; then it checks whether there is a free slot in the local array of object pointers: cpucache_t * cc; local_irq_save(save_flags); cc = cachep->cpudata[smp_processor_id( )]; if (cc->avail == cc->limit) { cc->avail -= cachep->batchcount; free_block(cachep, &((void *)(cc+1))[cc->avail], cachep->batchcount); } ((void *)(cc+1))[cc->avail++] = objp; local_irq_restore(save_flags); return; If there is at least one free slot in the local array, the function just sets it to the address of the object being freed. Otherwise, the function invokes free_block( ) to release a bunch of cachep- >batchcount objects to the slab allocator cache. The free_block(cachep,objpp,len) function acquires the cache spin lock and then releases len objects starting from the local array entry at address objpp: spin_lock(&cachep->spinlock); for ( ; len > 0; len--, objpp++) { slab_t * slabp = (slab_t *) mem_map[_ _pa(*objpp) >> PAGE_SHIFT].list.prev; unsigned int objnr = (*objpp - slabp->s_mem) / cachep->objsize; ((kmem_bufctl_t *)(slabp+1))[objnr] = slabp->free; slabp->free = objnr; if (--slabp->inuse == 0) { /* slab is now fully free */ list_del(&slabp->list); list_add(&slabp->list, &cachep->slabs_free); } else if (slabp->inuse+1 == cachep->num) { /* slab was full */ list_del(&slabp->list); list_add(&slabp->list, &cachep->slabs_partial); } } spin_unlock(&cachep->spinlock); The code that releases the objects to the slabs is identical to that of the uniprocessor case, so we don't discuss it further. 7.2.14 General Purpose Objects As stated earlier in Section 7.1.7, infrequent requests for memory areas are handled through a group of general caches whose objects have geometrically distributed sizes ranging from a minimum of 32 to a maximum of 131,072 bytes. Objects of this type are obtained by invoking the kmalloc( ) function: void * kmalloc(size_t size, int flags) { cache_sizes_t *csizep = cache_sizes; kmem_cache_t * cachep; for (; csizep->cs_size; csizep++) { if (size > csizep->cs_size) continue; if (flags & _ _GFP_DMA) cachep = csizep->cs_dmacahep; else cachep = csizep->cs_cachep; return _ _kmem_cache_alloc(cachep, flags); } return NULL; } The function uses the cache_sizes table to locate the nearest power-of-2 size to the requested size. It then calls kmem_cache_alloc( ) to allocate the object, passing to it either the cache descriptor for the page frames usable for ISA DMA or the cache descriptor for the "normal" page frames, depending on whether the caller specified the _ _GFP_DMA flag.[3] [3] Actually, for more efficiency, the code of kmem_cache_alloc( ) is copied inside the body of kmalloc( ). The _ _kmem_cache alloc( ) function, which implements kmem_cache_alloc( ), is declared inline. Objects obtained by invoking kmalloc( ) can be released by calling kfree( ): void kfree(const void *objp) { kmem_cache_t * c; unsigned long flags; if (!objp) return; local_irq_save(flags); c = (kmem_cache_t *) mem_map[_ _pa(objp) >> PAGE_SHIFT].list.next; _ _kmem_cache_free(c, (void *) objp); local_irq_restore(flags); } The proper cache descriptor is identified by reading the list.next subfield of the descriptor of the first page frame containing the memory area. The memory area is released by invoking kmem_cache_free( ).[4] [4] As for kmalloc( ), the code of kmem_cache_free( ) is copied inside kfree( ). _ _kmem_cache_free( ), which implements kmem_cache_free( ), is declared inline. I l@ve RuBoard I l@ve RuBoard 7.3 Noncontiguous Memory Area Management We already know that it is preferable to map memory areas into sets of contiguous page frames, thus making better use of the cache and achieving lower average memory access times. Nevertheless, if the requests for memory areas are infrequent, it makes sense to consider an allocation schema based on noncontiguous page frames accessed through contiguous linear addresses. The main advantage of this schema is to avoid external fragmentation, while the disadvantage is that it is necessary to fiddle with the kernel Page Tables. Clearly, the size of a noncontiguous memory area must be a multiple of 4,096. Linux uses noncontiguous memory areas in several ways — for instance, to allocate data structures for active swap areas (see Section 16.2.3), to allocate space for a module (see Appendix B), or to allocate buffers to some I/O drivers. 7.3.1 Linear Addresses of Noncontiguous Memory Areas To find a free range of linear addresses, we can look in the area starting from PAGE_OFFSET (usually 0xc0000000, the beginning of the fourth gigabyte). Figure 7-7 shows how the fourth gigabyte linear addresses are used: ● The beginning of the area includes the linear addresses that map the first 896 MB of RAM (see Section 2.5.4); the linear address that corresponds to the end of the directly mapped physical memory is stored in the high_memory variable. ● The end of the area contains the fix-mapped linear addresses (see Section 2.5.6). ● Starting from PKMAP_BASE (0xfe000000), we find the linear addresses used for the persistent kernel mapping of high-memory page frames (see Section 7.1.6 earlier in this chapter). ● The remaining linear addresses can be used for noncontiguous memory areas. A safety interval of size 8 MB (macro VMALLOC_OFFSET) is inserted between the end of the physical memory mapping and the first memory area; its purpose is to "capture" out-of-bounds memory accesses. For the same reason, additional safety intervals of size 4 KB are inserted to separate noncontiguous memory areas. Figure 7-7. The linear address interval starting from PAGE_OFFSET The VMALLOC_START macro defines the starting address of the linear space reserved for noncontiguous memory areas, while VMALLOC_END defines its ending address. 7.3.2 Descriptors of Noncontiguous Memory Areas Each noncontiguous memory area is associated with a descriptor of type struct vm_struct: struct vm_struct { unsigned long flags; void * addr; unsigned long size; struct vm_struct * next; }; These descriptors are inserted in a simple list by means of the next field; the address of the first element of the list is stored in the vmlist variable. Accesses to this list are protected by means of the vmlist_lock read/write spin lock. The addr field contains the linear address of the first memory cell of the area; the size field contains the size of the area plus 4,096 (which is the size of the previously mentioned inter-area safety interval). The get_vm_area( ) function creates new descriptors of type struct vm_struct; its parameter size specifies the size of the new memory area. The function is essentially equivalent to the following: struct vm_struct * get_vm_area(unsigned long size, unsigned long flags) { unsigned long addr; struct vm_struct **p, *tmp, *area; area = (struct vm_struct *) kmalloc(sizeof(*area), GFP_KERNEL); if (!area) return NULL; size += PAGE_SIZE; addr = VMALLOC_START; write_lock(&vmlist_lock); for (p = &vmlist; (tmp = *p) ; p = &tmp->next) { if (size + addr <= (unsigned long) tmp->addr) { area->flags = flags; area->addr = (void *) addr; area->size = size; area->next = *p; *p = area; write_unlock(&vmlist_lock); return area; } addr = tmp->size + (unsigned long) tmp->addr; if (addr + size > VMALLOC_END) { write_unlock(&vmlist_lock); kfree(area); return NULL; } } } The function first calls kmalloc( ) to obtain a memory area for the new descriptor. It then scans the list of descriptors of type struct vm_struct looking for an available range of linear addresses that includes at least size+4096 addresses. If such an interval exists, the function initializes the fields of the descriptor and terminates by returning the initial address of the noncontiguous memory area. Otherwise, when addr + size exceeds VMALLOC_END, get_vm_area( ) releases the descriptor and returns NULL. 7.3.3 Allocating a Noncontiguous Memory Area The vmalloc( ) function allocates a noncontiguous memory area to the kernel. The parameter size denotes the size of the requested area. If the function is able to satisfy the request, it then returns the initial linear address of the new area; otherwise, it returns a NULL pointer: void * vmalloc(unsigned long size) { void * addr; struct vm_struct *area; size = (size + PAGE_SIZE - 1) & PAGE_MASK; area = get_vm_area(size, VM_ALLOC); if (!area) return NULL; addr = area->addr; if (vmalloc_area_pages((unsigned long) addr, size, GFP_KERNEL|_ _GFP_HIGHMEM, 0x63)) { vfree(addr); return NULL; } return addr; } The function starts by rounding up the value of the size parameter to a multiple of 4,096 (the page frame size). Then vmalloc( ) invokes get_vm_area( ), which creates a new descriptor and returns the linear addresses assigned to the memory area. The flags field of the descriptor is initialized with the VM_ALLOC flag, which means that the linear address range is going to be used for a noncontiguous memory allocation (we'll see in Chapter 13 that vm_struct descriptors are also used to remap memory on hardware devices). Then the vmalloc( ) function invokes vmalloc_area_pages( ) to request noncontiguous page frames and terminates by returning the initial linear address of the noncontiguous memory area. The vmalloc_area_pages( ) function uses four parameters: address The initial linear address of the area. size The size of the area. gfp_mask The allocation flags passed to the buddy system allocator function. It is always set to GFP_KERNEL|_ _GFP_HIGHMEM. prot The protection bits of the allocated page frames. It is always set to 0x63, which corresponds to Present, Accessed, Read/Write, and Dirty. The function starts by assigning the linear address of the end of the area to the end local variable: end = address + size; The function then uses the pgd_offset_k macro to derive the entry in the master kernel Page Global Directory related to the initial linear address of the area; it then acquires the kernel Page Table spin lock: dir = pgd_offset_k(address); spin_lock(&init_mm.page_table_lock); The function then executes the following cycle: while (address < end) { pmd_t *pmd = pmd_alloc(&init_mm, dir, address); ret = -ENOMEM; if (!pmd) break; if (alloc_area_pmd(pmd, address, end - address, gfp_mask, prot)) break; address = (address + PGDIR_SIZE) & PGDIR_MASK; dir++; ret = 0; } spin_unlock(&init_mm.page_table_lock); return ret; In each cycle, it first invokes pmd_alloc( ) to create a Page Middle Directory for the new area and writes its physical address in the right entry of the kernel Page Global Directory. It then calls alloc_area_pmd( ) to allocate all the Page Tables associated with the new Page Middle Directory. It adds the constant 222—the size of the range of linear addresses spanned by a single Page Middle Directory—to the current value of address, and it increases the pointer dir to the Page Global Directory. The cycle is repeated until all Page Table entries referring to the noncontiguous memory area are set up. The alloc_area_pmd( ) function executes a similar cycle for all the Page Tables that a Page Middle Directory points to: while (address < end) { pte_t * pte = pte_alloc(&init_mm, pmd, address); if (!pte) return -ENOMEM; if (alloc_area_pte(pte, address, end - address)) return -ENOMEM; address = (address + PMD_SIZE) & PMD_MASK; pmd++; } The pte_alloc( ) function (see Section 2.5.2) allocates a new Page Table and updates the corresponding entry in the Page Middle Directory. Next, alloc_area_pte( ) allocates all the page frames corresponding to the entries in the Page Table. The value of address is increased by 222—the size of the linear address interval spanned by a single Page Table—and the cycle is repeated. The main cycle of alloc_area_pte( ) is: while (address < end) { unsigned long page; spin_unlock(&init_mm.page_table_lock); page_alloc(gfp_mask); spin_lock(&init_mm.page_table_lock); if (!page) return -ENOMEM; set_pte(pte, mk_pte(page, prot)); address += PAGE_SIZE; pte++; } Each page frame is allocated through page_alloc( ). The physical address of the new page frame is written into the Page Table by the set_pte and mk_pte macros. The cycle is repeated after adding the constant 4,096 (the length of a page frame) to address. Notice that the Page Tables of the current process are not touched by vmalloc_area_pages( ). Therefore, when a process in Kernel Mode accesses the noncontiguous memory area, a Page Fault occurs, since the entries in the process's Page Tables corresponding to the area are null. However, the Page Fault handler checks the faulty linear address against the master kernel Page Tables (which are init_mm.pgd Page Global Directory and its child Page Tables; see Section 2.5.5). Once the handler discovers that a master kernel Page Table includes a non-null entry for the address, it copies its value into the corresponding process's Page Table entry and resumes normal execution of the process. This mechanism is described in Section 8.4. 7.3.4 Releasing a Noncontiguous Memory Area The vfree( ) function releases noncontiguous memory areas. Its parameter addr contains the initial linear address of the area to be released. vfree( ) first scans the list pointed to by vmlist to find the address of the area descriptor associated with the area to be released: write_lock(&vmlist_lock); for (p = &vmlist ; (tmp = *p) ; p = &tmp->next) { if (tmp->addr == addr) { *p = tmp->next; vmfree_area_pages((unsigned long)(tmp->addr), tmp->size); write_unlock(&vmlist_lock); kfree(tmp); return; } } write_unlock(&vmlist_lock); printk("Trying to vfree( ) nonexistent vm area (%p)\n", addr); The size field of the descriptor specifies the size of the area to be released. The area itself is released by invoking vmfree_area_pages( ), while the descriptor is released by invoking kfree( ). The vmfree_area_pages( ) function takes two parameters: the initial linear address and the size of the area. It executes the following cycle to reverse the actions performed by vmalloc_area_pages( ): dir = pgd_offset_k(address); while (address < end) { free_area_pmd(dir, address, end - address); address = (address + PGDIR_SIZE) & PGDIR_MASK; dir++; } In turn, free_area_pmd( ) reverses the actions of alloc_area_pmd( ) in the cycle: while (address < end) { free_area_pte(pmd, address, end - address); address = (address + PMD_SIZE) & PMD_MASK; pmd++; } Again, free_area_pte( ) reverses the activity of alloc_area_pte( ) in the cycle: while (address < end) { pte_t page = *pte; pte_clear(pte); address += PAGE_SIZE; pte++; if (pte_none(page)) continue; if (pte_present(page)) { _ _free_page(pte_page(page)); continue; } printk("Whee... Swapped out page in kernel page table\n"); } Each page frame assigned to the noncontiguous memory area is released by means of the buddy system _ _free_ page( ) function. The corresponding entry in the Page Table is set to 0 by the pte_clear macro. As for vmalloc( ), the kernel modifies the entries of the master kernel Page Global Directory and its child Page Tables (see Section 2.5.5), but it leaves unchanged the entries of the process Page Tables mapping the fourth gigabyte. This is fine because the kernel never reclaims Page Middle Directories and Page Tables rooted at the master kernel Page Global Directory. For instance, suppose that a process in Kernel Mode accessed a noncontiguous memory area that later got released. The process's Page Global Directory entries are equal to the corresponding entries of the master kernel Page Global Directory, thanks to the mechanism explained in Section 8.4; they point to the same Page Middle Directories and Page Tables. The vmfree_area_pages( ) function clears only the entries of the Page Tables (without reclaiming the Page Tables themselves). Further accesses of the process to the released noncontiguous memory area will trigger Page Faults because of the null Page Table entries. However, the handler will consider such accesses a bug because the master kernel Page Tables do not include valid entries. I l@ve RuBoard I l@ve RuBoard Chapter 8. Process Address Space As seen in the previous chapter, a kernel function gets dynamic memory in a fairly straightforward manner by invoking one of a variety of functions: _ _get_free_pages( ) or pages_alloc( ) to get pages from the buddy system algorithm, kmem_cache_alloc( ) or kmalloc( ) to use the slab allocator for specialized or general-purpose objects, and vmalloc( ) to get a noncontiguous memory area. If the request can be satisfied, each of these functions returns a page descriptor address or a linear address identifying the beginning of the allocated dynamic memory area. These simple approaches work for two reasons: ● The kernel is the highest-priority component of the operating system. If a kernel function makes a request for dynamic memory, it must have a valid reason to issue that request, and there is no point in trying to defer it. ● The kernel trusts itself. All kernel functions are assumed to be error-free, so the kernel does not need to insert any protection against programming errors. When allocating memory to User Mode processes, the situation is entirely different: ● Process requests for dynamic memory are considered nonurgent. When a process's executable file is loaded, for instance, it is unlikely that the process will address all the pages of code in the near future. Similarly, when a process invokes malloc( ) to get additional dynamic memory, it doesn't mean the process will soon access all the additional memory obtained. Thus, as a general rule, the kernel tries to defer allocating dynamic memory to User Mode processes. ● Since user programs cannot be trusted, the kernel must be prepared to catch all addressing errors caused by processes in User Mode. As this chapter describes, the kernel succeeds in deferring the allocation of dynamic memory to processes by using a new kind of resource. When a User Mode process asks for dynamic memory, it doesn't get additional page frames; instead, it gets the right to use a new range of linear addresses, which become part of its address space. This interval is called a memory region. In the next section, we discuss how the process views dynamic memory. We then describe the basic components of the process address space in Section 8.3. Next, we examine in detail the role played by the Page Fault exception handler in deferring the allocation of page frames to processes and illustrate how the kernel creates and deletes whole process address spaces. Last, we discuss the APIs and system calls related to address space management. I l@ve RuBoard I l@ve RuBoard 8.1 The Process's Address Space The address space of a process consists of all linear addresses that the process is allowed to use. Each process sees a different set of linear addresses; the address used by one process bears no relation to the address used by another. As we shall see later, the kernel may dynamically modify a process address space by adding or removing intervals of linear addresses. The kernel represents intervals of linear addresses by means of resources called memory regions, which are characterized by an initial linear address, a length, and some access rights. For reasons of efficiency, both the initial address and the length of a memory region must be multiples of 4,096 so that the data identified by each memory region completely fills up the page frames allocated to it. Following are some typical situations in which a process gets new memory regions: ● When the user types a command at the console, the shell process creates a new process to execute the command. As a result, a fresh address space, thus a set of memory regions, is assigned to the new process (see Section 8.5 later in this chapter; also, see Chapter 20). ● A running process may decide to load an entirely different program. In this case, the process ID remains unchanged but the memory regions used before loading the program are released and a new set of memory regions is assigned to the process (see Section 20.4). ● A running process may perform a "memory mapping" on a file (or on a portion of it). In such cases, the kernel assigns a new memory region to the process to map the file (see Chapter 15). ● A process may keep adding data on its User Mode stack until all addresses in the memory region that map the stack have been used. In this case, the kernel may decide to expand the size of that memory region (see Section 8.4 later in this chapter). ● A process may create an IPC-shared memory region to share data with other cooperating processes. In this case, the kernel assigns a new memory region to the process to implement this construct (see Section 19.3.5). ● A process may expand its dynamic area (the heap) through a function such as malloc( ). As a result, the kernel may decide to expand the size of the memory region assigned to the heap (see Section 8.6 later in this chapter). Table 8-1 illustrates some of the system calls related to the previously mentioned tasks. With the exception of brk( ), which is discussed at the end of this chapter, the system calls are described in other chapters. Table 8-1. System calls related to memory region creation and deletion System call Description brk( ), sbrk( ) Changes the heap size of the process execve( ) Loads a new executable file, thus changing the process address space _exit( ) Terminates the current process and destroys its address space fork( ) Creates a new process, and thus a new address space mmap( ) Creates a memory mapping for a file, thus enlarging the process address space munmap( ) Destroys a memory mapping for a file, thus contracting the process address space shmat( ) Attaches a shared memory region shmdt( ) Detaches a shared memory region As we shall see in the later section Section 8.4, it is essential for the kernel to identify the memory regions currently owned by a process (the address space of a process) since that allows the Page Fault exception handler to efficiently distinguish between two types of invalid linear addresses that cause it to be invoked: ● Those caused by programming errors. ● Those caused by a missing page; even though the linear address belongs to the process's address space, the page frame corresponding to that address has yet to be allocated. The latter addresses are not invalid from the process's point of view; the kernel handles the Page Fault by providing the page frame and letting the process continue. I l@ve RuBoard I l@ve RuBoard 8.2 The Memory Descriptor All information related to the process address space is included in a data structure called a memory descriptor. This structure of type mm_struct is referenced by the mm field of the process descriptor. The fields of a memory descriptor are listed in Table 8-2. Table 8-2. The fields of the memory descriptor Type Field Description struct vm_area_struct * mmap Pointer to the head of the list of memory region objects rb_root_t mm_rb Pointer to the root of the red-black tree of memory region objects struct vm_area_struct * mmap_cache Pointer to the last referenced memory region object pgd_t * pgd Pointer to the Page Global Directory atomic_t mm_users Secondary usage counter atomic_t mm_count Main usage counter int map_count Number of memory regions struct rw_semaphore mmap_sem Memory regions' read/write semaphore spinlock_t page_table_lock Memory regions' and Page Tables' spin lock struct list_head mmlist Pointers to adjacent elements in the list of memory descriptors unsigned long start_code Initial address of executable code unsigned long end_code Final address of executable code unsigned long start_data Initial address of initialized data unsigned long end_data Final address of initialized data unsigned long start_brk Initial address of the heap unsigned long brk Current final address of the heap unsigned long start_stack Initial address of User Mode stack unsigned long arg_start Initial address of command-line arguments unsigned long arg_end Final address of command-line arguments unsigned long env_start Initial address of environment variables unsigned long env_end Final address of environment variables unsigned long rss Number of page frames allocated to the process unsigned long total_vm Size of the process address space (number of pages) unsigned long locked_vm Number of "locked" pages that cannot be swapped out (see Chapter 16) unsigned long def_flags Default access flags of the memory regions unsigned long cpu_vm_mask Bit mask for lazy TLB switches (see Chapter 2) unsigned long swap_address Last scanned linear address for swapping (see Chapter 16) unsigned int dumpable Flag that specifies whether the process can produce a core dump of the memory mm_context_t context Pointer to table for architecture-specific information (e.g., LDT's address in 80 x 86 platforms) All memory descriptors are stored in a doubly linked list. Each descriptor stores the address of the adjacent list items in the mmlist field. The first element of the list is the mmlist field of init_mm, the memory descriptor used by process 0 in the initialization phase. The list is protected against concurrent accesses in multiprocessor systems by the mmlist_lock spin lock. The number of memory descriptors in the list is stored in the mmlist_nr variable. The mm_users field stores the number of lightweight processes that share the mm_struct data structure (see Section 3.4.1). The mm_count field is the main usage counter of the memory descriptor; all "users" in mm_users count as one unit in mm_count. Every time the mm_count field is decremented, the kernel checks whether it becomes zero; if so, the memory descriptor is deallocated because it is no longer in use. We'll try to explain the difference between the use of mm_users and mm_count with an example. Consider a memory descriptor shared by two lightweight processes. Normally, its mm_users field stores the value 2, while its mm_count field stores the value 1 (both owner processes count as one). If the memory descriptor is temporarily lent to a kernel thread (see the next section), the kernel increments the mm_count field. In this way, even if both lightweight processes die and the mm_users field becomes zero, the memory descriptor is not released until the kernel thread finishes using it because the mm_count field remains greater than zero. If the kernel wants to be sure that the memory descriptor is not released in the middle of a lengthy operation, it might increment the mm_users field instead of mm_count (this is what the swap_out( ) function does; see Section 16.5). The final result is the same because the increment of mm_users ensures that mm_count does not become zero even if all lightweight processes that own the memory descriptor die. The mm_alloc( ) function is invoked to get a new memory descriptor. Since these descriptors are stored in a slab allocator cache, mm_alloc( ) calls kmem_cache_alloc( ), initializes the new memory descriptor, and sets the mm_count and mm_users field to 1. Conversely, the mmput( ) function decrements the mm_users field of a memory descriptor. If that field becomes 0, the function releases the Local Descriptor Table, the memory region descriptors (see later in this chapter), and the Page Tables referenced by the memory descriptor, and then invokes mmdrop( ). The latter function decrements mm_count and, if it becomes zero, releases the mm_struct data structure. The mmap, mm_rb, mmlist, and mmap_cache fields are discussed in the next section. 8.2.1 Memory Descriptor of Kernel Threads Kernel threads run only in Kernel Mode, so they never access linear addresses below TASK_SIZE (same as PAGE_OFFSET, usually 0xc0000000). Contrary to regular processes, kernel threads do not use memory regions, therefore most of the fields of a memory descriptor are meaningless for them. Since the Page Table entries that refer to the linear address above TASK_SIZE should always be identical, it does not really matter what set of Page Tables a kernel thread uses. To avoid useless TLB and cache flushes, kernel threads use the Page Tables of a regular process in Linux 2.4. To that end, two kinds of memory descriptor pointers are included in every memory descriptor: mm and active_mm. The mm field in the process descriptor points to the memory descriptor owned by the process, while the active_mm field points to the memory descriptor used by the process when it is in execution. For regular processes, the two fields store the same pointer. Kernel threads, however, do not own any memory descriptor, thus their mm field is always NULL. When a kernel thread is selected for execution, its active_mm field is initialized to the value of the active_mm of the previously running process (see Section 11.2.2.3). There is, however, a small complication. Whenever a process in Kernel Mode modifies a Page Table entry for a "high" linear address (above TASK_SIZE), it should also update the corresponding entry in the sets of Page Tables of all processes in the system. In fact, once set by a process in Kernel Mode, the mapping should be effective for all other processes in Kernel Mode as well. Touching the sets of Page Tables of all processes is a costly operation; therefore, Linux adopts a deferred approach. We already mentioned this deferred approach in Section 7.3: every time a high linear address has to be remapped (typically by vmalloc( ) or vfree( )), the kernel updates a canonical set of Page Tables rooted at the swapper_pg_dir master kernel Page Global Directory (see Section 2.5.5). This Page Global Directory is pointed to by the pgd field of a master memory descriptor, which is stored in the init_mm variable.[1] [1] We mentioned in Section 3.4.2 that the swapper kernel thread uses init_mm during the initialization phase. However, swapper never uses this memory descriptor once the initialization phase completes. Later, in Section 8.4.5, we'll describe how the Page Fault handler takes care of spreading the information stored in the canonical Page Tables when effectively needed. I l@ve RuBoard I l@ve RuBoard 8.3 Memory Regions Linux implements a memory region by means of an object of type vm_area_struct; its fields are shown in Table 8-3. Table 8-3. The fields of the memory region object Type Field Description struct mm_struct * vm_mm Pointer to the memory descriptor that owns the region unsigned long vm_start First linear address inside the region unsigned long vm_end First linear address after the region struct vm_area_struct * vm_next Next region in the process list pgprot_t vm_page_prot Access permissions for the page frames of the region unsigned long vm_flags Flags of the region rb_node_t vm_rb Data for the red-black tree (see later in this chapter) struct vm_area_struct * vm_next_share Pointer to the next element in the file memory mapping list struct vm_area_struct ** vm_pprev_share Pointer to previous element in the file memory mapping list struct vm_operations_struct * vm_ops Pointer to the methods of the memory region unsigned long vm_pgoff Offset in mapped file, if any (see Chapter 15) struct file * vm_file Pointer to the file object of the mapped file, if any unsigned long vm_raend End of current read-ahead window of the mapped file (see Section 15.2.4) void * vm_private_data Pointer to private data of the memory region Each memory region descriptor identifies a linear address interval. The vm_start field contains the first linear address of the interval, while the vm_end field contains the first linear address outside of the interval; vm_end - vm_start thus denotes the length of the memory region. The vm_mm field points to the mm_struct memory descriptor of the process that owns the region. We shall describe the other fields of vm_area_struct as they come up. Memory regions owned by a process never overlap, and the kernel tries to merge regions when a new one is allocated right next to an existing one. Two adjacent regions can be merged if their access rights match. As shown in Figure 8-1, when a new range of linear addresses is added to the process address space, the kernel checks whether an already existing memory region can be enlarged (case a). If not, a new memory region is created (case b). Similarly, if a range of linear addresses is removed from the process address space, the kernel resizes the affected memory regions (case c). In some cases, the resizing forces a memory region to split into two smaller ones (case d ).[2] [2] Removing a linear address interval may theoretically fail because no free memory is available for a new memory descriptor. Figure 8-1. Adding or removing a linear address interval The vm_ops field points to a vm_operations_struct data structure, which stores the methods of the memory region. Only three methods are defined: open Invoked when the memory region is added to the set of regions owned by a process. close Invoked when the memory region is removed from the set of regions owned by a process. nopage Invoked by the Page Fault exception handler when a process tries to access a page not present in RAM whose linear address belongs to the memory region (see the later section Section 8.4). 8.3.1 Memory Region Data Structures All the regions owned by a process are linked in a simple list. Regions appear in the list in ascending order by memory address; however, successive regions can be separated by an area of unused memory addresses. The vm_next field of each vm_area_struct element points to the next element in the list. The kernel finds the memory regions through the mmap field of the process memory descriptor, which points to the first memory region descriptor in the list. The map_count field of the memory descriptor contains the number of regions owned by the process. A process may own up to MAX_MAP_COUNT different memory regions (this value is usually set to 65,536). Figure 8-2 illustrates the relationships among the address space of a process, its memory descriptor, and the list of memory regions. Figure 8-2. Descriptors related to the address space of a process A frequent operation performed by the kernel is to search the memory region that includes a specific linear address. Since the list is sorted, the search can terminate as soon as a memory region that ends after the specific linear address is found. However, using the list is convenient only if the process has very few memory regions—let's say less than a few tens of them. Searching, inserting elements, and deleting elements in the list involve a number of operations whose times are linearly proportional to the list length. Although most Linux processes use very few memory regions, there are some large applications, such as object-oriented databases, that one might consider "pathological" because they have many hundreds or even thousands of regions. In such cases, the memory region list management becomes very inefficient, hence the performance of the memory-related system calls degrades to an intolerable point. Therefore, Linux 2.4 stores memory descriptors in data structures called red-black trees.[3] In an red-black tree, each element (or node) usually has two children: a left child and a right child. The elements in the tree are sorted. For each node N, all elements of the subtree rooted at the left child of N precede N, while, conversely, all elements of the subtree rooted at the right child of N follow N (see Figure 8-3(a); the key of the node is written inside the node itself. [3] Up to Version 2.4.9, the Linux kernel used another type of balanced search tree called AVL tree. Moreover, a red-black tree must satisfy four additional rules: 1. Every node must be either red or black. 2. The root of the tree must be black. 3. The children of a red node must be black. 4. Every path from a node to a descendant leaf must contain the same number of black nodes. When counting the number of black nodes, null pointers are counted as black nodes. Figure 8-3. Example of red-black trees These four rules ensure that any red-black tree with n internal nodes has a height of at most 2log(n + 1). Searching an element in a red-black tree is thus very efficient because it requires operations whose execution time is linearly proportional to the logarithm of the tree size. In other words, doubling the number of memory regions adds just one more iteration to the operation. Inserting and deleting an element in a red-black tree is also efficient because the algorithm can quickly traverse the tree to locate the position at which the element will be inserted or from which it will be removed. Any new node must be inserted as a leaf and colored red. If the operation breaks the rules, a few nodes of the tree must be moved or recolored. For instance, suppose that an element having the value 4 must be inserted in the red-black tree shown in Figure 8-3(a). Its proper position is the right child of the node that has key 3, but once it is inserted, the red node that has the value 3 has a red child, thus breaking rule 3. To satisfy the rule, the color of nodes that have the values 3, 4, and 7 is changed. This operation, however, breaks rule 4, thus the algorithm performs a "rotation" on the subtree rooted at the node that has the key 19, producing the new red-black tree shown in Figure 8-3(b). This looks complicated, but inserting or deleting an element in a red-black tree requires a small number of operations—a number linearly proportional to the logarithm of the tree size. Therefore, to store the memory regions of a process, Linux uses both a linked list and a red-black tree. Both data structures contain pointers to the same memory region descriptors, When inserting or removing a memory region descriptor, the kernel searches the previous and next elements through the red-black tree and uses them to quickly update the list without scanning it. The head of the linked list is referenced by the mmap field of the memory descriptor. Any memory region object stores the pointer to the next element of the list in the vm_next field. The head of the red-black tree is referred by the mm_rb field of the memory descriptor. Any memory region object stores the color of the node, as well as the pointers to the parent, the left child, and the right child, into the vm_rb field of type rb_node_t. In general, the red-black tree is used to locate a region including a specific address, while the linked list is mostly useful when scanning the whole set of regions. 8.3.2 Memory Region Access Rights Before moving on, we should clarify the relation between a page and a memory region. As mentioned in Chapter 2, we use the term "page" to refer both to a set of linear addresses and to the data contained in this group of addresses. In particular, we denote the linear address interval ranging between 0 and 4,095 as page 0, the linear address interval ranging between 4,096 and 8,191 as page 1, and so forth. Each memory region therefore consists of a set of pages that have consecutive page numbers. We have already discussed two kinds of flags associated with a page: ● A few flags such as Read/Write, Present, or User/Supervisor stored in each Page Table entry (see Section 2.4.1). ● A set of flags stored in the flags field of each page descriptor (see Section 7.1). The first kind of flag is used by the 80 x 86 hardware to check whether the requested kind of addressing can be performed; the second kind is used by Linux for many different purposes (see Table 7-2). We now introduce a third kind of flags: those associated with the pages of a memory region. They are stored in the vm_flags field of the vm_area_struct descriptor (see Table 8-4). Some flags offer the kernel information about all the pages of the memory region, such as what they contain and what rights the process has to access each page. Other flags describe the region itself, such as how it can grow. Table 8-4. The memory region flags Flag name Description VM_READ Pages can be read. VM_WRITE Pages can be written. VM_EXEC Pages can be executed. VM_SHARED Pages can be shared by several processes. VM_MAYREAD VM_READ flag may be set. VM_MAYWRITE VM_WRITE flag may be set. VM_MAYEXEC VM_EXEC flag may be set. VM_MAYSHARE VM_SHARE flag may be set. VM_GROWSDOWN The region can expand toward lower addresses. VM_GROWSUP The region can expand toward higher addresses. VM_SHM The region is used for IPC's shared memory. VM_DENYWRITE The region maps a file that cannot be opened for writing. VM_EXECUTABLE The region maps an executable file. VM_LOCKED Pages in the region are locked and cannot be swapped out. VM_IO The region maps the I/O address space of a device. VM_SEQ_READ The application accesses the pages sequentially. VM_RAND_READ The application accesses the pages in a truly random order. VM_DONTCOPY Does not copy the region when forking a new process. VM_DONTEXPAND Forbids region expansion through mremap( ) system call. VM_RESERVED Does not swap out the region. Page access rights included in a memory region descriptor may be combined arbitrarily. It is possible, for instance, to allow the pages of a region to be executed but not read. To implement this protection scheme efficiently, the read, write, and execute access rights associated with the pages of a memory region must be duplicated in all the corresponding Page Table entries so that checks can be directly performed by the Paging Unit circuitry. In other words, the page access rights dictate what kinds of access should generate a Page Fault exception. As we shall see shortly, the job of figuring out what caused the Page Fault is delegated by Linux to the Page Fault handler, which implements several page-handling strategies. The initial values of the Page Table flags (which must be the same for all pages in the memory region, as we have seen) are stored in the vm_ page_ prot field of the vm_area_struct descriptor. When adding a page, the kernel sets the flags in the corresponding Page Table entry according to the value of the vm_ page_ prot field. However, translating the memory region's access rights into the page protection bits is not straightforward for the following reasons: ● In some cases, a page access should generate a Page Fault exception even when its access type is granted by the page access rights specified in the vm_flags field of the corresponding memory region. For instance, as we shall see in Section 8.4.4 later in this chapter, the kernel may wish to store two identical, writable private pages (whose VM_SHARE flags are cleared) belonging to two different processes into the same page frame; in this case, an exception should be generated when either one of the processes tries to modify the page. ● 80 x 86 processors's Page Tables have just two protection bits, namely the Read/Write and User/Supervisor flags. Moreover, the User/Supervisor flag of any page included in a memory region must always be set, since the page must always be accessible by User Mode processes. To overcome the hardware limitation of the 80 x 86 microprocessors, Linux adopts the following rules: ● The read access right always implies the execute access right. ● The write access right always implies the read access right. Moreover, to correctly defer the allocation of page frames through the Section 8.4.4 technique (see later in this chapter), the page frame is write-protected whenever the corresponding page must not be shared by several processes. Therefore, the 16 possible combinations of the read, write, execute, and share access rights are scaled down to the following three: ● If the page has both write and share access rights, the Read/Write bit is set. ● If the page has the read or execute access right but does not have either the write or the share access right, the Read/Write bit is cleared. ● If the page does not have any access rights, the Present bit is cleared so that each access generates a Page Fault exception. However, to distinguish this condition from the real page- not-present case, Linux also sets the Page size bit to 1.[4] [4] You might consider this use of the Page size bit to be a dirty trick, since the bit was meant to indicate the real page size. But Linux can get away with the deception because the 80 x 86 chip checks the Page size bit in Page Directory entries, but not in Page Table entries. The downscaled protection bits corresponding to each combination of access rights are stored in the protection_map array. 8.3.3 Memory Region Handling Having the basic understanding of data structures and state information that control memory handling, we can look at a group of low-level functions that operate on memory region descriptors. They should be considered auxiliary functions that simplify the implementation of do_mmap( ) and do_munmap( ). Those two functions, which are described in Section 8.3.4 and Section 8.3.5 later in this chapter, enlarge and shrink the address space of a process, respectively. Working at a higher level than the functions we consider here, they do not receive a memory region descriptor as their parameter, but rather the initial address, the length, and the access rights of a linear address interval. 8.3.3.1 Finding the closest region to a given address: find_vma( ) The find_vma( ) function acts on two parameters: the address mm of a process memory descriptor and a linear address addr. It locates the first memory region whose vm_end field is greater than addr and returns the address of its descriptor; if no such region exists, it returns a NULL pointer. Notice that the region selected by find_vma( ) does not necessarily include addr because addr may lie outside of any memory region. Each memory descriptor includes a mmap_cache field that stores the descriptor address of the region that was last referenced by the process. This additional field is introduced to reduce the time spent in looking for the region that contains a given linear address. Locality of address references in programs makes it highly likely that if the last linear address checked belonged to a given region, the next one to be checked belongs to the same region. The function thus starts by checking whether the region identified by mmap_cache includes addr. If so, it returns the region descriptor pointer: vma = mm->mmap_cache; if (vma && vma->vm_end > addr && vma->vm_start <= addr) return vma; Otherwise, the memory regions of the process must be scanned, and the function looks up the memory region in the red-black tree: rb_node = mm->mm_rb.rb_node; vma = NULL; while (rb_node) { vma_tmp = rb_entry(rb_node, struct vm_area_struct, vm_rb); if (vma_tmp->vm_end > addr) { vma = vma_tmp; if (vma_tmp->vm_start <= addr) break; rb_node = rb_node->rb_left; } else rb_node = rb_node->rb_right; } if (vma) mm->mmap_cache = vma; return vma; The function uses the rb_entry macro, which derives from a pointer to a node of the red-black tree the address of the corresponding memory region descriptor. The kernel also defines the find_vma_prev( ) function (which returns the descriptor addresses of the memory region that precedes the linear address given as parameter and of the memory region that follows it) and the find_vma_prepare( ) function (which locates the position of the new leaf in the red-black tree that corresponds to a given linear address and returns the addresses of the preceding memory region and of the parent node of the leaf to be inserted). 8.3.3.2 Finding a region that overlaps a given interval: find_vma_intersection( ) The find_vma_intersection( ) function finds the first memory region that overlaps a given linear address interval; the mm parameter points to the memory descriptor of the process, while the start_addr and end_addr linear addresses specify the interval: vma = find_vma(mm,start_addr); if (vma && end_addr <= vma->vm_start) vma = NULL; return vma; The function returns a NULL pointer if no such region exists. To be exact, if find_vma( ) returns a valid address but the memory region found starts after the end of the linear address interval, vma is set to NULL. 8.3.3.3 Finding a free interval: arch_get_unmapped_area( ) The arch_get_unmapped_area( ) function searches the process address space to find an available linear address interval. The len parameter specifies the interval length, while the addr parameter may specify the address from which the search is started. If the search is successful, the function returns the initial address of the new interval; otherwise, it returns the error code - ENOMEM. if (len > TASK_SIZE) return -ENOMEM; addr = (addr + 0xfff) & 0xfffff000; if (addr && addr + len <= TASK_SIZE) { vma = find_vma(current->mm, addr); if (!vma || addr + len <= vma->vm_start) return addr; } addr = (TASK_SIZE/3 + 0xfff) & 0xfffff000; for (vma = find_vma(current->mm, addr); ; vma = vma->vm_next) { if (addr + len > TASK_SIZE) return -ENOMEM; if (!vma || addr + len <= vma->vm_start) return addr; addr = vma->vm_end; } The function starts by checking to make sure the interval length is within the limit imposed on User Mode linear addresses, usually 3 GB. If addr is different from zero, the function tries to allocate the interval starting from addr. To be on the safe side, the function rounds up the value of addr to a multiple of 4 KB. If addr is 0 or the previous search failed, the search's starting point is set to one- third of the User Mode linear address space. Starting from addr, the function then repeatedly invokes find_vma( ) with increasing values of addr to find the required free interval. During this search, the following cases may occur: ● The requested interval is larger than the portion of linear address space yet to be scanned (addr + len > TASK_SIZE). Since there are not enough linear addresses to satisfy the request, return -ENOMEM. ● The hole following the last scanned region is not large enough (vma != NULL && vma- >vm_start < addr + len). Consider the next region. ● If neither one of the preceding conditions holds, a large enough hole has been found. Return addr. 8.3.3.4 Inserting a region in the memory descriptor list: insert_vm_struct( ) insert_vm_struct( ) inserts a vm_area_struct structure in the memory region object list and red-black tree of a memory descriptor. It uses two parameters: mm, which specifies the address of a process memory descriptor, and vma, which specifies the address of the vm_area_struct object to be inserted. The vm_start and vm_end fields of the memory region object must have already been initialized. The function invokes the find_vma_prepare( ) function to look up the position in the red-black tree mm->mm_rb where vma should go. Then insert_vm_struct( ) invokes the vma_link( ) function, which in turn: 1. Acquires the mm->page_table_lock spin lock. 2. Inserts the memory region in the linked list referenced by mm->mmap. 3. Inserts the memory region in the red-black tree mm->mm_rb. 4. Releases the mm->page_table_lock spin lock. 5. Increments by 1 the mm->map_count counter. If the region contains a memory-mapped file, the vma_link( ) function performs additional tasks that are described in Chapter 16. The kernel also defines the _ _insert_vm_struct( ) function, which is identical to insert_vm_struct( ) but doesn't acquire any lock before modifying the memory region data structures referenced by mm. The kernel uses it when it is sure that no concurrent accesses to the memory region data structures can happen—for instance, because it already acquired a suitable lock. The _ _vma_unlink( ) function receives as parameter a memory descriptor address mm and two memory region object addresses vma and prev. Both memory regions should belong to mm, and prev should precede vma in the memory region ordering. The function removes vma from the linked list and the red-black tree of the memory descriptor. 8.3.4 Allocating a Linear Address Interval Now let's discuss how new linear address intervals are allocated. To do this, the do_mmap( ) function creates and initializes a new memory region for the current process. However, after a successful allocation, the memory region could be merged with other memory regions defined for the process. The function uses the following parameters: file and offset File descriptor pointer file and file offset offset are used if the new memory region will map a file into memory. This topic is discussed in Chapter 15. In this section, we assume that no memory mapping is required and that file and offset are both NULL. addr This linear address specifies where the search for a free interval must start. len The length of the linear address interval. prot This parameter specifies the access rights of the pages included in the memory region. Possible flags are PROT_READ, PROT_WRITE, PROT_EXEC, and PROT_NONE. The first three flags mean the same things as the VM_READ, VM_WRITE, and VM_EXEC flags. PROT_NONE indicates that the process has none of those access rights. flag This parameter specifies the remaining memory region flags: MAP_GROWSDOWN, MAP_LOCKED, MAP_DENYWRITE, and MAP_EXECUTABLE Their meanings are identical to those of the flags listed in Table 8-4. MAP_SHARED and MAP_PRIVATE The former flag specifies that the pages in the memory region can be shared among several processes; the latter flag has the opposite effect. Both flags refer to the VM_SHARED flag in the vm_area_struct descriptor. MAP_ANONYMOUS No file is associated with the memory region (see Chapter 15). MAP_FIXED The initial linear address of the interval must be exactly the one specified in the addr parameter. MAP_NORESERVE The function doesn't have to do a preliminary check on the number of free page frames. The do_mmap( ) function performs some preliminary checks on the value of offset and then executes the do_mmap_pgoff() function. Assuming that the new interval of linear address does not map a file on disk, the latter function executes the following steps: 1. Checks whether the parameter values are correct and whether the request can be satisfied. In particular, it checks for the following conditions that prevent it from satisfying the request: ❍ The linear address interval has zero length or includes addresses greater than TASK_SIZE. ❍ The process has already mapped too many memory regions, so the value of the map_count field of its mm memory descriptor exceeds MAX_MAP_COUNT. ❍ The flag parameter specifies that the pages of the new linear address interval must be locked in RAM, and the number of pages locked by the process exceeds the threshold stored in the rlim[RLIMIT_MEMLOCK].rlim_cur field of the process descriptor. If any of the preceding conditions holds, do_mmap_pgoff( ) terminates by returning a negative value. If the linear address interval has a zero length, the function returns without performing any action. 2. Obtains a linear address interval for the new region; if the MAP_FIXED flag is set, a check is made on the addr value. Otherwise, the arch_get_unmapped_area( ) function is invoked to get it: if (flags & MAP_FIXED) { if (addr + len > TASK_SIZE) return -ENOMEM; if (addr & ~PAGE_MASK) return -EINVAL; } else addr = arch_get_unmapped_area(file, addr, len, pgoff, flags); 3. Computes the flags of the new memory region by combining the values stored in the prot and flags parameters: vm_flags = calc_vm_flags(prot,flags) | mm->def_flags | VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC; if (flags & MAP_SHARED) vm_flags |= VM_SHARED | VM_MAYSHARE; The calc_vm_flags( ) function sets the VM_READ, VM_WRITE, and VM_EXEC flags in vm_flags only if the corresponding PROT_READ, PROT_WRITE, and PROT_EXEC flags in prot are set; it also sets the VM_GROWSDOWN, VM_DENYWRITE, and VM_EXECUTABLE flags in vm_flags only if the corresponding MAP_GROWSDOWN, MAP_DENYWRITE, and MAP_EXECUTABLE flags in flags are set. A few other flags are set to 1 in vm_flags: VM_MAYREAD, VM_MAYWRITE, VM_MAYEXEC, the default flags for all memory regions in mm- >def_flags,[5] and both VM_SHARED and VM_MAYSHARE if the memory region has to be shared with other processes. [5] Actually, the def_flags field of the memory descriptor is modified only by the mlockall( ) system call, which can be used to set the VM_LOCKED flag, thus locking all future pages of the calling process in RAM. 4. Invokes find_vma_prepare( ) to locate the object of the memory region that shall precede the new interval, as well as the position of the new region in the red-black tree: for (;;) { vma = find_vma_prepare(mm, addr, &prev, &rb_link, &rb_parent); if (!vma || vma->vm_start >= addr + len) break; if (do_munmap(mm, addr, len)) return -ENOMEM; } The find_vma_prepare( ) function also checks whether a memory region that overlaps the new interval already exists. This occurs when the function returns a non-NULL address pointing to a region that starts before the end of the new interval. In this case, do_mmap_pgoff( ) invokes do_munmap( ) to remove the new interval and then repeats the whole step (see the later section Section 8.3.5). 5. Checks whether inserting the new memory region causes the size of the process address space (mm->total_vm<vm_mm = mm; vma->vm_start = addr; vma->vm_end = addr + len; vma->vm_flags = vm_flags; vma->vm_page_prot = protection_map[vm_flags & 0x0f]; vma->vm_ops = NULL; vma->vm_pgoff = pgoff; vma->vm_file = NULL; vma->vm_private_data = NULL; vma->vm_raend = 0; 10. If the MAP_SHARED flag is set (and the new memory region doesn't map a file on disk), the region is used for IPC shared memory. The function invokes shmem_zero_setup( ) to initialize it (see Chapter 19). 11. Invokes vma_link( ) to insert the new region in the memory region list and red-black tree (see the earlier section Section 8.3.3.4). 12. Increments the size of the process address space stored in the total_vm field of the memory descriptor. 13. If the VM_LOCKED flag is set, increments the counter of locked pages mm->locked_vm: if (vm_flags & VM_LOCKED) { mm->locked_vm += len >> PAGE_SHIFT; make_pages_present(addr, addr + len); } The make_pages_present( ) function is invoked to allocate all the pages of the memory region in succession and lock them in RAM. The function, in turn, invokes get_user_pages( ) as follows: write = (vma->vm_flags & VM_WRITE) != 0; get_user_pages(current, current->mm, addr, len, write, 0, NULL, NULL); The get_user_pages( ) function cycles through all starting linear addresses of the pages between addr and addr+len; for each of them, it invokes follow_page( ) to check whether there is a mapping to a physical page in the current's Page Tables. If no such physical page exists, get_user_pages( ) invokes handle_mm_fault( ), which, as we shall see in Section 8.4.2, allocates one page frame and sets its Page Table entry according to the vm_flags field of the memory region descriptor. 14. Finally, terminates by returning the linear address of the new memory region. 8.3.5 Releasing a Linear Address Interval The do_munmap( ) function deletes a linear address interval from the address space of the current process. The parameters are the starting address addr of the interval and its length len. The interval to be deleted does not usually correspond to a memory region; it may be included in one memory region or span two or more regions. The function goes through two main phases. First, it scans the list of memory regions owned by the process and removes all regions that overlap the linear address interval. In the second phase, the function updates the process Page Tables and reinserts a downsized version of the memory regions that were removed during the first phase. 8.3.5.1 First phase: scanning the memory regions The do_munmap( ) function executes the following steps: 1. Performs some preliminary checks on the parameter values. If the linear address interval includes addresses greater than TASK_SIZE, if addr is not a multiple of 4,096, or if the linear address interval has a zero length, it returns the error code -EINVAL. 2. Locates the first memory region that overlaps the linear address interval to be deleted: mpnt = find_vma_prev(current->mm, addr, &prev); if (!mpnt || mpnt->vm_start >= addr + len) return 0; 3. If the linear address interval is located inside a memory region, its deletion splits the region into two smaller ones. In this case, do_munmap( ) checks whether current is allowed to obtain an additional memory region: if ((mpnt->vm_start < addr && mpnt->vm_end > addr + len) && current->mm->map_count > MAX_MAP_COUNT) return -ENOMEM; 4. Attempts to get a new vm_area_struct descriptor. There may be no need for it, but the function makes the request anyway so that it can terminate right away if the allocation fails. This cautious approach simplifies the code since it allows an easy error exit. 5. Builds up a list that includes all descriptors of the memory regions that overlap the linear address interval. This list is created by setting the vm_next field of the memory region descriptor (temporarily) so it points to the previous item in the list; this field thus acts as a backward link. As each region is added to this backward list, a local variable named free points to the last inserted element. The regions inserted in the list are also removed from the list of memory regions owned by the process and from the red-black tree (by means of the rb_erase( ) function): npp = (prev ? &prev->vm_next : ¤t->mm->mmap); free = NULL; spin_lock(¤t->mm->page_table_lock); for ( ; mpnt && mpnt->vm_start < addr + len; mpnt = *npp) { *npp = mpnt->vm_next; mpnt->vm_next = free; free = mpnt; rb_erase(&mpnt->vm_rb, ¤t->mm->mm_rb); } current->mm->mmap_cache = NULL; spin_unlock(¤t->mm->page_table_lock); 8.3.5.2 Second phase: updating the Page Tables A while cycle is used to scan the list of memory regions built in the first phase, starting with the memory region descriptor that free points to. In each iteration, the mpnt local variable points to the descriptor of a memory region in the list. The map_count field of the current->mm memory descriptor is decremented (since the region has been removed in the first phase from the list of regions owned by the process) and a check is made (by means of two question-mark conditional expressions) to determine whether the mpnt region must be eliminated or simply downsized: current->mm->map_count--; st = addr < mpnt->vm_start ? mpnt->vm_start : addr; end = addr+len; end = end > mpnt->vm_end ? mpnt->vm_end : end; size = end - st; The st and end local variables delimit the linear address interval in the mpnt memory region that should be deleted; the size local variable specifies the length of the interval. Next, do_munmap( ) releases the page frames allocated for the pages included in the interval from st to end: zap_page_range(mm, st, size); The zap_page_range( ) function deallocates the page frames included in the interval from st to end and updates the corresponding Page Table entries. The function invokes in nested fashion the zap_pmd_range( ) and zap_pte_range( ) functions for scanning the Page Tables; the latter function clears the Page Table entries and frees the corresponding page frames (or slot in a swap area; see Chapter 14). While doing this, zap_pte_range( ) also invalidates the TLB entries corresponding to the interval from st to end. The last action performed in each iteration of the do_munmap( ) loop is to check whether a downsized version of the mpnt memory region must be reinserted in the list of regions of current: extra = unmap_fixup(mm, mpnt, st, size, extra); The unmap_fixup( ) function considers four possible cases: 1. The memory region has been totally canceled. It returns the address of the previously allocated memory region object (see Step 4 in the earlier section Section 8.3.5.1), which can be released by invoking kmem_cache_free( ). 2. Only the lower part of the memory region has been removed: (mpnt->vm_start < st) && (mpnt->vm_end == end) In this case, it updates the vm_end field of mnpt, invokes _ _insert_vm_struct( ) to insert the downsized region in the list of regions belonging to the process, and returns the address of the previously allocated memory region object. 3. Only the upper part of the memory region has been removed: (mpnt->vm_start == st) && (mpnt->vm_end > end) In this case, it updates the vm_start field of mnpt, invokes _ _insert_vm_struct( ) to insert the downsized region in the list of regions belonging to the process, and returns the address of the previously allocated memory object. 4. The linear address interval is in the middle of the memory region: (mpnt->vm_start < st) && (mpnt->vm_end > end) It updates the vm_start and vm_end fields of mnpt and of the previously allocated extra memory region object so that they refer to the linear address intervals, respectively, from mpnt->vm_start to st and from end to mpnt->vm_end. Then it invokes _ _insert_vm_struct( ) twice to insert the two regions in the list of regions belonging to the process and in the red-black tree, and returns NULL, thus preserving the memory region object previously allocated. This terminates the description of what must be done in a single iteration of the second-phase loop of do_munmap( ). After handling all the memory region descriptors in the list built during the first phase, do_munmap( ) checks if the additional extra memory descriptor has been used. If the address returned by unmap_fixup( ) is NULL, the descriptor has been used; otherwise, do_munmap( ) invokes kmem_cache_free( ) to release it. Finally, do_munmap( ) invokes the free_pgtables( ) function: it again scans the Page Table entries corresponding to the linear address interval just removed and reclaims the page frames that store unused Page Tables. I l@ve RuBoard I l@ve RuBoard 8.4 Page Fault Exception Handler As stated previously, the Linux Page Fault exception handler must distinguish exceptions caused by programming errors from those caused by a reference to a page that legitimately belongs to the process address space but simply hasn't been allocated yet. The memory region descriptors allow the exception handler to perform its job quite efficiently. The do_page_fault( ) function, which is the Page Fault interrupt service routine for the 80 x 86 architecture, compares the linear address that caused the Page Fault against the memory regions of the current process; it can thus determine the proper way to handle the exception according to the scheme that is illustrated in Figure 8-4. Figure 8-4. Overall scheme for the Page Fault handler In practice, things are a lot more complex because the Page Fault handler must recognize several particular subcases that fit awkwardly into the overall scheme, and it must distinguish several kinds of legal access. A detailed flow diagram of the handler is illustrated in Figure 8-5. Figure 8-5. The flow diagram of the Page Fault handler The identifiers vmalloc_fault, good_area, bad_area, and no_context are labels appearing in do_page_fault( ) that should help you to relate the blocks of the flow diagram to specific lines of code. The do_ page_fault( ) function accepts the following input parameters: ● The regs address of a pt_regs structure containing the values of the microprocessor registers when the exception occurred. ● A 3-bit error_code, which is pushed on the stack by the control unit when the exception occurred (see Section 4.2.4). The bits have the following meanings. ❍ If bit 0 is clear, the exception was caused by an access to a page that is not present (the Present flag in the Page Table entry is clear); otherwise, if bit 0 is set, the exception was caused by an invalid access right. ❍ If bit 1 is clear, the exception was caused by a read or execute access; if set, the exception was caused by a write access. ❍ If bit 2 is clear, the exception occurred while the processor was in Kernel Mode; otherwise, it occurred in User Mode. The first operation of do_ page_fault( ) consists of reading the linear address that caused the Page Fault. When the exception occurs, the CPU control unit stores that value in the cr2 control register: asm("movl %%cr2,%0":"=r" (address)); if (regs->eflags & 0x00000200) local_irq_enable(); tsk = current; The linear address is saved in the address local variable. The function also ensures that local interrupts are enabled if they were enabled before the fault and saves the pointers to the process descriptor of current in the tsk local variable. As shown at the top of Figure 8-5, do_ page_fault( ) checks whether the faulty linear address belongs to the fourth gigabyte and the exception was caused by the kernel trying to access a nonexisting page frame: if (address >= TASK_SIZE && !(error_code & 0x101)) goto vmalloc_fault; The code at label vmalloc_fault takes care of faults that were likely caused by accessing a noncontiguous memory area in Kernel Mode; we describe this case in the later section Section 8.4.5. Next, the handler checks whether the exception occurred while handling an interrupt or executing a kernel thread (remember that the mm field of the process descriptor is always NULL for kernel threads): info.i_code = SEGV_MAPERR; if (in_interrupt( ) || !tsk->mm) goto no_context; In both cases, do_ page_fault( ) does not try to compare the linear address with the memory regions of current, since it would not make any sense: interrupt handlers and kernel threads never use linear addresses below TASK_SIZE, and thus never rely on memory regions. (See the next section for information on the info local variable and a description of the code at the no_context label.) Let's suppose that the Page Fault did not occur in an interrupt handler or in a kernel thread. Then the function must inspect the memory regions owned by the process to determine whether the faulty linear address is included in the process address space: down_read(&tsk->mm->mmap_sem); vma = find_vma(tsk->mm, address); if (!vma) goto bad_area; if (vma->vm_start <= address) goto good_area; If vma is NULL, there is no memory region ending after address, and thus the faulty address is certainly bad. On the other hand, the first memory region ending after address might not include address; if it does, the function jumps to the code at label good_area. If none of the two "if" conditions are satisfied, the function has determined that address is not included in any memory region; however, it must perform an additional check, since the faulty address may have been caused by a push or pusha instruction on the User Mode stack of the process. Let's make a short digression to explain how stacks are mapped into memory regions. Each region that contains a stack expands toward lower addresses; its VM_GROWSDOWN flag is set, so the value of its vm_end field remains fixed while the value of its vm_start field may be decreased. The region boundaries include, but do not delimit precisely, the current size of the User Mode stack. The reasons for the fuzz factor are: ● The region size is a multiple of 4 KB (it must include complete pages) while the stack size is arbitrary. ● Page frames assigned to a region are never released until the region is deleted; in particular, the value of the vm_start field of a region that includes a stack can only decrease; it can never increase. Even if the process executes a series of pop instructions, the region size remains unchanged. It should now be clear how a process that has filled up the last page frame allocated to its stack may cause a Page Fault exception: the push refers to an address outside of the region (and to a nonexistent page frame). Notice that this kind of exception is not caused by a programming error; thus it must be handled separately by the Page Fault handler. We now return to the description of do_ page_fault( ), which checks for the case described previously: if (!(vma->vm_flags & VM_GROWSDOWN)) goto bad_area; if (error_code & 4 /* User Mode */ && address + 32 < regs->esp) goto bad_area; if (expand_stack(vma, address)) goto bad_area; goto good_area; If the VM_GROWSDOWN flag of the region is set and the exception occurred in User Mode, the function checks whether address is smaller than the regs->esp stack pointer (it should be only a little smaller). Since a few stack-related assembly language instructions (like pusha) perform a decrement of the esp register only after the memory access, a 32-byte tolerance interval is granted to the process. If the address is high enough (within the tolerance granted), the code invokes the expand_stack( ) function to check whether the process is allowed to extend both its stack and its address space; if everything is OK, it sets the vm_start field of vma to address and returns 0; otherwise, it returns 1. Note that the preceding code skips the tolerance check whenever the VM_GROWSDOWN flag of the region is set and the exception did not occur in User Mode. These conditions mean that the kernel is addressing the User Mode stack and that the code should always run expand_stack( ). 8.4.1 Handling a Faulty Address Outside the Address Space If address does not belong to the process address space, do_page_fault( ) proceeds to execute the statements at the label bad_area. If the error occurred in User Mode, it sends a SIGSEGV signal to current (see Section 10.2) and terminates: bad_area: up_read(&tsk->mm->mmap_sem); if (error_code & 4) { /* User Mode */ tsk->thread.cr2 = address; tsk->thread.error_code = error_code; tsk->thread.trap_no = 14; info.si_signo = SIGSEGV; info.si_errno = 0; info.si_addr = (void *) address; force_sig_info(SIGSEGV, &info, tsk); return; } The force_sig_info( ) function makes sure that the process does not ignore or block the SIGSEGV signal, and sends the signal to the User Mode process while passing some additional information in the info local variable (see Section 10.2.2). The info.si_code field is already set to SEGV_MAPERR (if the exception was due to a nonexisting page frame) or to SEGV_ACCERR (if the exception was due to an invalid access to an existing page frame). If the exception occurred in Kernel Mode (bit 2 of error_code is clear), there are still two alternatives: ● The exception occurred while using some linear address that has been passed to the kernel as parameter of a system call. ● The exception is due to a real kernel bug. The function distinguishes these two alternatives as follows: no_context: if ((fixup = search_exception_table(regs->eip)) != 0) { regs->eip = fixup; return; } In the first case, it jumps to a "fixup code," which typically sends a SIGSEGV signal to current or terminates a system call handler with a proper error code (see Section 9.2.6). In the second case, the function prints a complete dump of the CPU registers, the Kernel Mode stack on the console, and on a system message buffer, and then kills the current process by invoking the do_exit( ) function (see Chapter 20). This is the so-called "Kernel oops" error, named after the message displayed. The dumped values can be used by kernel hackers to reconstruct the conditions that triggered the bug, and thus find and correct it. 8.4.2 Handling a Faulty Address Inside the Address Space If address belongs to the process address space, do_ page_fault( ) proceeds to the statement labeled good_area: good_area: info.si_code = SEGV_ACCERR; write = 0; if (error_code & 2) { /* write access */ if (!(vma->vm_flags & VM_WRITE)) goto bad_area; write++; } else /* read access */ if ((error_code & 1) || !(vma->vm_flags & (VM_READ | VM_EXEC))) goto bad_area; If the exception was caused by a write access, the function checks whether the memory region is writable. If not, it jumps to the bad_area code; if so, it sets the write local variable to 1. If the exception was caused by a read or execute access, the function checks whether the page is already present in RAM. In this case, the exception occurred because the process tried to access a privileged page frame (one whose User/Supervisor flag is clear) in User Mode, so the function jumps to the bad_area code.[6] If the page is not present, the function also checks whether the memory region is readable or executable. [6] However, this case should never happen, since the kernel does not assign privileged page frames to the processes. If the memory region access rights match the access type that caused the exception, the handle_mm_fault( ) function is invoked to allocate a new page frame: survive: ret = handle_mm_fault(tsk->mm, vma, address, write); if (ret == 1 || ret == 2) { if (ret == 1) tsk->min_flt++; else tsk->maj_flt++; up_read(&tsk->mm->mmap_sem); return; } The handle_mm_fault( ) function returns 1 or 2 if it succeeded in allocating a new page frame for the process. The value 1 indicates that the Page Fault has been handled without blocking the current process; this kind of Page Fault is called minor fault. The value 2 indicates that the Page Fault forced the current process to sleep (most likely because time was spent while filling the page frame assigned to the process with data read from disk); a Page Fault that blocks the current process is called a major fault. The function can also returns -1 (for not enough memory) or 0 (for any other error). If handle_mm_fault( ) returns the value 0, a SIGBUS signal is sent to the process: if (!ret) { up_read(&tsk->mm->mmap_sem); tsk->thread.cr2 = address; tsk->thread.error_code = error_code; tsk->thread.trap_no = 14; info.si_signo = SIGBUS; info.si_errno = 0; info.si_code = BUS_ADRERR; info.si_addr = (void *) address; force_sig_info(SIGBUS, &info, tsk); if (!(error_code & 4)) /* Kernel Mode */ goto no_context; } If handle_mm_fault( ) cannot allocate the new page frame, the kernel usually kills the current process. However, if current is the init process, it is just put at the end of the run queue and the scheduler is invoked; once init resumes its execution, handle_mm_fault( ) is executed again: if (ret == -1) { up_read(&tsk->mm->mmap_sem); if (tsk->pid != 1) { if (error_code & 4) /* User Mode */ do_exit(SIGKILL); goto no_context; } tsk->policy |= SCHED_YIELD; schedule(); down_read(&tsk->mm->mmap_sem); goto survive; } The handle_mm_fault( ) function acts on four parameters: mm A pointer to the memory descriptor of the process that was running on the CPU when the exception occurred vma A pointer to the descriptor of the memory region, including the linear address that caused the exception address The linear address that caused the exception write_access Set to 1 if tsk attempted to write in address and to 0 if tsk attempted to read or execute it The function starts by checking whether the Page Middle Directory and the Page Table used to map address exist. Even if address belongs to the process address space, the corresponding Page Tables might not have been allocated, so the task of allocating them precedes everything else: spin_lock(&mm->page_table_lock); pgd = pgd_offset(mm, address); pmd = pmd_alloc(mm, pgd, address); if (pmd) { pte = pte_alloc(mm, pmd, address); if (pte) return handle_pte_fault(mm, vma, address, write_access, pte); } spin_unlock(&mm->page_table_lock); return -1; The pgd local variable contains the Page Global Directory entry that refers to address; pmd_alloc( ) is invoked to allocate, if needed, a new Page Middle Directory.[7] pte_alloc( ) is then invoked to allocate, if needed, a new Page Table. If both operations are successful, the pte local variable points to the Page Table entry that refers to address. [7] On 80 x 86 microprocessors, this kind of allocation never occurs since the Page Middle Directories are either included in the Page Global Directory (PAE not enabled) or allocated together with the Page Global Directory (PAE enabled). The handle_pte_fault( ) function is then invoked to inspect the Page Table entry corresponding to address and to determine how to allocate a new page frame for the process: ● If the accessed page is not present—that is, if it is not already stored in any page frame—the kernel allocates a new page frame and initializes it properly; this technique is called demand paging. ● If the accessed page is present but is marked read only—i.e., if it is already stored in a page frame—the kernel allocates a new page frame and initializes its contents by copying the old page frame data; this technique is called Copy On Write. 8.4.3 Demand Paging The term demand paging denotes a dynamic memory allocation technique that consists of deferring page frame allocation until the last possible moment—until the process attempts to address a page that is not present in RAM, thus causing a Page Fault exception. The motivation behind demand paging is that processes do not address all the addresses included in their address space right from the start; in fact, some of these addresses may never be used by the process. Moreover, the program locality principle (see Section 2.4.7) ensures that, at each stage of program execution, only a small subset of the process pages are really referenced, and therefore the page frames containing the temporarily useless pages can be used by other processes. Demand paging is thus preferable to global allocation (assigning all page frames to the process right from the start and leaving them in memory until program termination) since it increases the average number of free page frames in the system and therefore allows better use of the available free memory. From another viewpoint, it allows the system as a whole to get a better throughput with the same amount of RAM. The price to pay for all these good things is system overhead: each Page Fault exception induced by demand paging must be handled by the kernel, thus wasting CPU cycles. Fortunately, the locality principle ensures that once a process starts working with a group of pages, it sticks with them without addressing other pages for quite a while. Thus, Page Fault exceptions may be considered rare events. An addressed page may not be present in main memory for the following reasons: ● The page was never accessed by the process. The kernel can recognize this case since the Page Table entry is filled with zeros—i.e., the pte_none macro returns the value 1. ● The page was already accessed by the process, but its content is temporarily saved on disk. The kernel can recognize this case since the Page Table entry is not filled with zeros (however, the Present flag is cleared since the page is not present in RAM). The handle_ pte_fault( ) function distinguishes the two cases by inspecting the Page Table entry that refers to address: entry = *pte; if (!pte_present(entry)) { if (pte_none(entry)) return do_no_page(mm, vma, address, write_access, pte); return do_swap_page(mm, vma, address, pte, entry, write_access); } We'll examine the case in which the page is saved on disk (using the do_swap_ page( ) function) in Section 16.6. In the other situation, when the page was never accessed, the do_no_page( ) function is invoked. There are two ways to load the missing page, depending on whether the page is mapped to a disk file. The function determines this by checking the nopage method of the vma memory region object, which points to the function that loads the missing page from disk into RAM if the page is mapped to a file. Therefore, the possibilities are: ● The vma->vm_ops->nopage field is not NULL. In this case, the memory region maps a disk file and the field points to the function that loads the page. This case is covered in Section 15.2.4 and in Section 19.3.5. ● Either the vm_ops field or the vma->vm_ops->nopage field is NULL. In this case, the memory region does not map a file on disk—i.e., it is an anonymous mapping. Thus, do_no_ page( ) invokes the do_anonymous_page( ) function to get a new page frame: if (!vma->vm_ops || !vma->vm_ops->nopage) return do_anonymous_page(mm, vma, page_table, write_access, address); The do_anonymous_page( ) function handles write and read requests separately: if (write_access) { spin_unlock(&mm->page_table_lock); page = alloc_page(GFP_HIGHUSER); addr = kmap_atomic(page, KM_USER0); memset((void *)(addr), 0, PAGE_SIZE); kunmap_atomic(addr, KM_USER0); spin_lock(&mm->page_table_lock); mm->rss++; entry = pte_mkwrite(pte_mkdirty(mk_pte(page, vma->vm_page_prot))); lru_cache_add(page); mark_page_accessed(page); set_pte(page_table, entry); spin_unlock(&mm->page_table_lock); return 1; } When handling a write access, the function invokes alloc_page( ) and fills the new page frame with zeros by using the memset macro. The function then increments the min_flt field of tsk to keep track of the number of minor Page Faults caused by the process. Next, the function increments the rss field of the memory descriptor to keep track of the number of page frames allocated to the process.[8] The Page Table entry is then set to the physical address of the page frame, which is marked as writable and dirty. The lru_cache_add( ) and mark_page_accessed( ) functions insert the new page frame in the swap-related data structures; we discuss them in Chapter 16. [8] Linux records the number of minor and major Page Faults for each process. This information, together with several other statistics, may be used to tune the system. Conversely, when handling a read access, the content of the page is irrelevant because the process is addressing it for the first time. It is safer to give a page filled with zeros to the process rather than an old page filled with information written by some other process. Linux goes one step further in the spirit of demand paging. There is no need to assign a new page frame filled with zeros to the process right away, since we might as well give it an existing page called zero page, thus deferring further page frame allocation. The zero page is allocated statically during kernel initialization in the empty_zero_page variable (an array of 1,024 long integers filled with zeros); it is stored in the fifth page frame (starting from physical address 0x00004000) and can be referenced by means of the ZERO_PAGE macro. The Page Table entry is thus set with the physical address of the zero page: entry = pte_wrprotect(mk_pte(ZERO_PAGE, vma->vm_page_prot)); set_pte(page_table, entry); spin_unlock(&mm->page_table_lock); return 1; Since the page is marked as nonwritable, if the process attempts to write in it, the Copy On Write mechanism is activated. Only then does the process get a page of its own to write in. The mechanism is described in the next section. 8.4.4 Copy On Write First-generation Unix systems implemented process creation in a rather clumsy way: when a fork( ) system call was issued, the kernel duplicated the whole parent address space in the literal sense of the word and assigned the copy to the child process. This activity was quite time consuming since it required: ● Allocating page frames for the Page Tables of the child process ● Allocating page frames for the pages of the child process ● Initializing the Page Tables of the child process ● Copying the pages of the parent process into the corresponding pages of the child process This way of creating an address space involved many memory accesses, used up many CPU cycles, and completely spoiled the cache contents. Last but not least, it was often pointless because many child processes start their execution by loading a new program, thus discarding entirely the inherited address space (see Chapter 20). Modern Unix kernels, including Linux, follow a more efficient approach called Copy On Write (COW). The idea is quite simple: instead of duplicating page frames, they are shared between the parent and the child process. However, as long as they are shared, they cannot be modified. Whenever the parent or the child process attempts to write into a shared page frame, an exception occurs. At this point, the kernel duplicates the page into a new page frame that it marks as writable. The original page frame remains write-protected: when the other process tries to write into it, the kernel checks whether the writing process is the only owner of the page frame; in such a case, it makes the page frame writable for the process. The count field of the page descriptor is used to keep track of the number of processes that are sharing the corresponding page frame. Whenever a process releases a page frame or a Copy On Write is executed on it, its count field is decremented; the page frame is freed only when count becomes NULL. Let's now describe how Linux implements COW. When handle_ pte_fault( ) determines that the Page Fault exception was caused by an access to a page present in memory, it executes the following instructions: if (pte_present(entry)) { if (write_access) { if (!pte_write(entry)) return do_wp_page(mm, vma, address, pte, entry); entry = pte_mkdirty(entry); } entry = pte_mkyoung(entry); set_pte(pte, entry); flush_tlb_page(vma, address); spin_unlock(&mm->page_table_lock); return 1; } The handle_pte_fault( ) function is architecture-independent: it considers any possible violation of the page access rights. However, in the 80 x 86 architecture, if the page is present then the access was for writing and the page frame is write-protected (see Section 8.4.2). Thus, the do_wp_page( ) function is always invoked. The do_wp_page( ) function starts by deriving the page descriptor of the page frame referenced by the Page Table entry involved in the Page Fault exception. Next, the function determines whether the page must really be duplicated. If only one process owns the page, Copy On Write does not apply and the process should be free to write the page. Basically, the function reads the count field of the page descriptor: if it is equal to 1, COW must not be done. Actually, the check is slightly more complicated, since the count field is also incremented when the page is inserted into the swap cache (see Section 16.3). However, when COW is not to be done, the page frame is marked as writable so that it does not cause further Page Fault exceptions when writes are attempted: set_pte(page_table, pte_mkyoung(pte_mkdirty(pte_mkwrite(pte)))); flush_tlb_page(vma, address); spin_unlock(&mm->page_table_lock); return 1; /* minor fault */ If the page is shared among several processes by means of the COW, the function copies the content of the old page frame (old_page) into the newly allocated one (new_page). To avoid race conditions, the usage counter of old_page is incremented before starting the copy operation: old_page = pte_page(pte); atomic_inc(&old_page->count); spin_unlock(&mm->page_table_lock); new_page = alloc_page(GFP_HIGHUSER); vto = kmap_atomic(new_page, KM_USER0); if (old_page == ZERO_PAGE) { memset((void *)vto, 0, PAGE_SIZE); } else { vfrom = kmap_atomic(old_page, KM_USER1); memcpy((void *)vto, (void *)vfrom, PAGE_SIZE); kunmap_atomic(vfrom, KM_USER1); } kunmap_atomic(vto, KM_USER0); If the old page is the zero page, the new frame is efficiently filled with zeros by using the memset macro. Otherwise, the page frame content is copied using the memcpy macro. Special handling for the zero page is not strictly required, but it improves the system performance because it preserves the microprocessor hardware cache by making fewer address references. Since the allocation of a page frame can block the process, the function checks whether the Page Table entry has been modified since the beginning of the function (pte and *page_table do not have the same value). In this case, the new page frame is released, the usage counter of old_page is decrement (to undo the increment made previously), and the function terminates. If everything looks OK, the physical address of the new page frame is finally written into the Page Table entry and the corresponding TLB register is invalidated: set_pte(pte, pte_mkwrite(pte_mkdirty(mk_pte(new_page, vma->vm_page_prot)))); flush_tlb_page(vma, address); lru_cache_add(new_page); spin_unlock(&mm->page_table_lock); The lru_cache_add( ) inserts the new page frame in the swap-related data structures; see Chapter 16 for its description. Finally, do_wp_page( ) decrements the usage counter of old_page twice. The first decrement undoes the safety increment made before copying the page frame contents; the second decrement reflects the fact that the current process no longer owns the page frame. 8.4.5 Handling Noncontiguous Memory Area Accesses We have seen in Section 7.3 that the kernel is quite lazy in updating the Page Table entries corresponding to noncontiguous memory areas. In fact, the vmalloc( ) and vfree( ) functions limit themselves to update the master kernel Page Tables (i.e., the Page Global Directory init_mm.pgd and its child Page Tables). However, once the kernel initialization phase ends, the master kernel Page Tables are not directly used by any process or kernel thread. Thus, consider the first time that a process in Kernel Mode accesses a noncontiguous memory area. When translating the linear address into a physical address, the CPU's memory management unit encounters a null Page Table entry and raises a Page Fault. However, the handler recognizes this special case because the exception occurred in Kernel Mode and the faulty linear address is greater than TASK_SIZE. Thus, the handler checks the corresponding master kernel Page Table entry: vmalloc_fault: asm("movl %%cr3,%0":"=r" (pgd)); pgd = _ _pgd_offset(address) + (pgd_t *) _ _va(pgd); pgd_k = init_mm.pgd + _ _pgd_offset(address); if (!pgd_present(*pgd_k)) goto no_context; set_pgd(pgd, *pgd_k); pmd = pmd_offset(pgd, address); pmd_k = pmd_offset(pgd_k, address); if (!pmd_present(*pmd_k)) goto no_context; set_pmd(pmd, *pmd_k); pte_k = pte_offset(pmd_k, address); if (!pte_present(*pte_k)) goto no_context; return; The pgd local variable is loaded with the Page Global Directory address of the current process, which is stored in the cr3 register,[9] while the pgd_k local variable is loaded with the master kernel Page Global Directory. If the entry corresponding to the faulty linear address is null, the function jumps to the code at the no_context label (see the earlier section Section 8.4.1). Otherwise, the entry is copied into the corresponding entry of the process Page Global Directory. Then the whole operation is repeated with the master Page Middle Directory entry and, subsequently, with the master Page Table entry. [9] The kernel doesn't use current->mm->pgd to derive the address because this fault can occur at any instant, even during a process switch. I l@ve RuBoard I l@ve RuBoard 8.5 Creating and Deleting a Process Address Space Of the six typical cases mentioned earlier in Section 8.1, in which a process gets new memory regions, the first one—issuing a fork( ) system call—requires the creation of a whole new address space for the child process. Conversely, when a process terminates, the kernel destroys its address space. In this section, we discuss how these two activities are performed by Linux. 8.5.1 Creating a Process Address Space In Section 3.4.1, we mentioned that the kernel invokes the copy_mm( ) function while creating a new process. This function creates the process address space by setting up all Page Tables and memory descriptors of the new process. Each process usually has its own address space, but lightweight processes can be created by calling clone( ) with the CLONE_VM flag set. These processes share the same address space; that is, they are allowed to address the same set of pages. Following the COW approach described earlier, traditional processes inherit the address space of their parent: pages stay shared as long as they are only read. When one of the processes attempts to write one of them, however, the page is duplicated; after some time, a forked process usually gets its own address space that is different from that of the parent process. Lightweight processes, on the other hand, use the address space of their parent process. Linux implements them simply by not duplicating address space. Lightweight processes can be created considerably faster than normal processes, and the sharing of pages can also be considered a benefit so long as the parent and children coordinate their accesses carefully. If the new process has been created by means of the clone( ) system call and if the CLONE_VM flag of the flag parameter is set, copy_mm( ) gives the clone (tsk) the address space of its parent (current): if (clone_flags & CLONE_VM) { atomic_inc(¤t->mm->mm_users); tsk->mm = current->mm; tsk->active_mm = current->mm; return 0; } If the CLONE_VM flag is not set, copy_mm( ) must create a new address space (even though no memory is allocated within that address space until the process requests an address). The function allocates a new memory descriptor, stores its address in the mm field of the new process descriptor tsk, and then initializes its fields: tsk->mm = kmem_cache_alloc(mm_cachep, SLAB_KERNEL); tsk->active_mm = tsk->mm; memcpy(tsk->mm, current->mm, sizeof(*tsk->mm)); atomic_set(&tsk->mm->mm_users, 1); atomic_set(&tsk->mm->mm_count, 1); init_rwsem(&tsk->mm->mmap_sem); tsk->mm->page_table_lock = SPIN_LOCK_UNLOCKED; tsk->mm->pgd = pgd_alloc(tsk->mm); Remember that the pgd_alloc( ) macro allocates a Page Global Directory for the new process. The dup_mmap( ) function is then invoked to duplicate both the memory regions and the Page Tables of the parent process: down_write(¤t->mm->mmap_sem); dup_mmap(tsk->mm); up_write(¤t->mm->mmap_sem); copy_segments(tsk, tsk->mm); The dup_mmap( ) function inserts the new memory descriptor tsk->mm in the global list of memory descriptors. Then it scans the list of regions owned by the parent process, starting from the one pointed by current->mm->mmap. It duplicates each vm_area_struct memory region descriptor encountered and inserts the copy in the list of regions owned by the child process. Right after inserting a new memory region descriptor, dup_mmap( ) invokes copy_page_range( ) to create, if necessary, the Page Tables needed to map the group of pages included in the memory region and to initialize the new Page Table entries. In particular, any page frame corresponding to a private, writable page (VM_SHARE flag off and VM_MAYWRITE flag on) is marked as read-only for both the parent and the child, so that it will be handled with the Copy On Write mechanism. Before terminating, dup_mmap( ) also creates the red-black tree of memory regions of the child process by invoking the build_mmap_rb( ) function. Finally, copy_mm( ) invokes copy_segments( ), which initializes the architecture- dependent portion of the child's memory descriptor. Essentially, if the parent has a custom LDT, a copy of it is also assigned to the child. 8.5.2 Deleting a Process Address Space When a process terminates, the kernel invokes the exit_mm( ) function to release the address space owned by that process: mm_release(); if (tsk->mm) { atomic_inc(&tsk->mm->mm_count); mm = tsk->mm; tsk->mm = NULL; enter_lazy_tlb(mm, current, smp_processor_id()); mmput(mm); } The mm_release( ) function wakes up any process sleeping in the tsk->vfork_done completion (see Section 5.3.8). Typically, the corresponding wait queue is nonempty only if the exiting process was created by means of the vfork( ) system call (see Section 3.4.1). The processor is also put in lazy TLB mode (see Chapter 2). I l@ve RuBoard I l@ve RuBoard 8.6 Managing the Heap Each Unix process owns a specific memory region called heap, which is used to satisfy the process's dynamic memory requests. The start_brk and brk fields of the memory descriptor delimit the starting and ending addresses, respectively, of that region. The following C library functions can be used by the process to request and release dynamic memory: malloc(size) Requests size bytes of dynamic memory; if the allocation succeeds, it returns the linear address of the first memory location. calloc(n,size) Requests an array consisting of n elements of size size; if the allocation succeeds, it initializes the array components to 0 and returns the linear address of the first element. free(addr) Releases the memory region allocated by malloc( ) or calloc( ) that has an initial address of addr. brk(addr) Modifies the size of the heap directly; the addr parameter specifies the new value of current->mm->brk, and the return value is the new ending address of the memory region (the process must check whether it coincides with the requested addr value). sbrk(incr) Is similar to brk( ), except that the incr parameter specifies the increment or decrement of the heap size in bytes. The brk( ) function differs from the other functions listed because it is the only one implemented as a system call. All the other functions are implemented in the C library by using brk( ) and mmap( ). When a process in User Mode invokes the brk( ) system call, the kernel executes the sys_brk(addr) function (see Chapter 9). This function first verifies whether the addr parameter falls inside the memory region that contains the process code; if so, it returns immediately: mm = current->mm; down_write(&mm->mmap_sem); if (addr < mm->end_code) { out: up_write(&mm->mmap_sem); return mm->brk; } Since the brk( ) system call acts on a memory region, it allocates and deallocates whole pages. Therefore, the function aligns the value of addr to a multiple of PAGE_SIZE and compares the result with the value of the brk field of the memory descriptor: newbrk = (addr + 0xfff) & 0xfffff000; oldbrk = (mm->brk + 0xfff) & 0xfffff000; if (oldbrk == newbrk) { mm->brk = addr; goto out; } If the process asked to shrink the heap, sys_brk( ) invokes the do_munmap( ) function to do the job and then returns: if (addr <= mm->brk) { if (!do_munmap(mm, newbrk, oldbrk-newbrk)) mm->brk = addr; goto out; } If the process asked to enlarge the heap, sys_brk( ) first checks whether the process is allowed to do so. If the process is trying to allocate memory outside its limit, the function simply returns the original value of mm->brk without allocating more memory: rlim = current->rlim[RLIMIT_DATA].rlim_cur; if (rlim < RLIM_INFINITY && addr - mm->start_data > rlim) goto out; The function then checks whether the enlarged heap would overlap some other memory region belonging to the process and, if so, returns without doing anything: if (find_vma_intersection(mm, oldbrk, newbrk+PAGE_SIZE)) goto out; The last check before proceeding to the expansion consists of verifying whether the available free virtual memory is sufficient to support the enlarged heap (see the earlier section Section 8.3.4): if (!vm_enough_memory((newbrk-oldbrk) >> PAGE_SHIFT)) goto out; If everything is OK, the do_brk( ) function is invoked with the MAP_FIXED flag set. If it returns the oldbrk value, the allocation was successful and sys_brk( ) returns the value addr; otherwise, it returns the old mm->brk value: if (do_brk(oldbrk, newbrk-oldbrk) == oldbrk) mm->brk = addr; goto out; The do_brk( ) function is actually a simplified version of do_mmap( ) that handles only anonymous memory regions. Its invocation might be considered equivalent to: do_mmap(NULL, oldbrk, newbrk-oldbrk, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_FIXED|MAP_PRIVATE, 0) Of course, do_brk( ) is slightly faster than do_mmap( ) because it avoids several checks on the memory region object fields by assuming that the memory region doesn't map a file on disk. I l@ve RuBoard I l@ve RuBoard Chapter 9. System Calls Operating systems offer processes running in User Mode a set of interfaces to interact with hardware devices such as the CPU, disks, and printers. Putting an extra layer between the application and the hardware has several advantages. First, it makes programming easier by freeing users from studying low-level programming characteristics of hardware devices. Second, it greatly increases system security, since the kernel can check the accuracy of the request at the interface level before attempting to satisfy it. Last but not least, these interfaces make programs more portable since they can be compiled and executed correctly on any kernel that offers the same set of interfaces. Unix systems implement most interfaces between User Mode processes and hardware devices by means of system calls issued to the kernel. This chapter examines in detail how Linux implements system calls that User Mode programs issue to the kernel. I l@ve RuBoard I l@ve RuBoard 9.1 POSIX APIs and System Calls Let's start by stressing the difference between an application programmer interface (API) and a system call. The former is a function definition that specifies how to obtain a given service, while the latter is an explicit request to the kernel made via a software interrupt. Unix systems include several libraries of functions that provide APIs to programmers. Some of the APIs defined by the libc standard C library refer to wrapper routines (routines whose only purpose is to issue a system call). Usually, each system call has a corresponding wrapper routine, which defines the API that application programs should employ. The converse is not true, by the way—an API does not necessarily correspond to a specific system call. First of all, the API could offer its services directly in User Mode. (For something abstract like math functions, there may be no reason to make system calls.) Second, a single API function could make several system calls. Moreover, several API functions could make the same system call, but wrap extra functionality around it. For instance, in Linux, the malloc( ), calloc( ), and free( ) APIs are implemented in the libc library. The code in this library keeps track of the allocation and deallocation requests and uses the brk( ) system call to enlarge or shrink the process heap (see Section 8.6). The POSIX standard refers to APIs and not to system calls. A system can be certified as POSIX-compliant if it offers the proper set of APIs to the application programs, no matter how the corresponding functions are implemented. As a matter of fact, several non-Unix systems have been certified as POSIX-compliant, since they offer all traditional Unix services in User Mode libraries. From the programmer's point of view, the distinction between an API and a system call is irrelevant — the only things that matter are the function name, the parameter types, and the meaning of the return code. From the kernel designer's point of view, however, the distinction does matter since system calls belong to the kernel, while User Mode libraries don't. Most wrapper routines return an integer value, whose meaning depends on the corresponding system call. A return value of -1 usually indicates that the kernel was unable to satisfy the process request. A failure in the system call handler may be caused by invalid parameters, a lack of available resources, hardware problems, and so on. The specific error code is contained in the errno variable, which is defined in the libc library. Each error code is defined as a macro constant, which yields a corresponding positive integer value. The POSIX standard specifies the macro names of several error codes. In Linux, on 80 x 86 systems, these macros are defined in the header file include/asm-i386/errno.h. To allow portability of C programs among Unix systems, the include/asm-i386/errno.h header file is included, in turn, in the standard /usr/include/errno.h C library header file. Other systems have their own specialized subdirectories of header files. I l@ve RuBoard I l@ve RuBoard 9.2 System Call Handler and Service Routines When a User Mode process invokes a system call, the CPU switches to Kernel Mode and starts the execution of a kernel function. In Linux a system call must be invoked by executing the int $0x80 assembly language instruction, which raises the programmed exception that has vector 128 (see Section 4.4.1 and Section 4.2.4, both in Chapter 4). Since the kernel implements many different system calls, the process must pass a parameter called the system call number to identify the required system call; the eax register is used for this purpose. As we shall see in Section 9.2.3 later in this chapter, additional parameters are usually passed when invoking a system call. All system calls return an integer value. The conventions for these return values are different from those for wrapper routines. In the kernel, positive or 0 values denote a successful termination of the system call, while negative values denote an error condition. In the latter case, the value is the negation of the error code that must be returned to the application program in the errno variable. The errno variable is not set or used by the kernel. Instead, the wrapper routines handles the task of setting this variable after a return from a system call. The system call handler, which has a structure similar to that of the other exception handlers, performs the following operations: ● Saves the contents of most registers in the Kernel Mode stack (this operation is common to all system calls and is coded in assembly language). ● Handles the system call by invoking a corresponding C function called the system call service routine. ● Exits from the handler by means of the ret_from_sys_call( ) function (which is coded in assembly language). The name of the service routine associated with the xyz( ) system call is usually sys_xyz( ); there are, however, a few exceptions to this rule. Figure 9-1 illustrates the relationships between the application program that invokes a system call, the corresponding wrapper routine, the system call handler, and the system call service routine. The arrows denote the execution flow between the functions. Figure 9-1. Invoking a system call To associate each system call number with its corresponding service routine, the kernel uses a system call dispatch table , which is stored in the sys_call_table array and has NR_syscalls entries (usually 256). The nth entry contains the service routine address of the system call having number n. The NR_syscalls macro is just a static limit on the maximum number of implementable system calls; it does not indicate the number of system calls actually implemented. Indeed, any entry of the dispatch table may contain the address of the sys_ni_syscall( ) function, which is the service routine of the "nonimplemented" system calls; it just returns the error code -ENOSYS. 9.2.1 Initializing System Calls The trap_init( ) function, invoked during kernel initialization, sets up the Interrupt Descriptor Table (IDT) entry corresponding to vector 128 (i.e., 0x80) as follows: set_system_gate(0x80, &system_call); The call loads the following values into the gate descriptor fields (see Section 4.4.1): Segment Selector The _ _KERNEL_CS Segment Selector of the kernel code segment. Offset The pointer to the system_call( ) exception handler. Type Set to 15. Indicates that the exception is a Trap and that the corresponding handler does not disable maskable interrupts. DPL (Descriptor Privilege Level) Set to 3. This allows processes in User Mode to invoke the exception handler (see Section 4.2.4). 9.2.2 The system_call( ) Function The system_call( ) function implements the system call handler. It starts by saving the system call number and all the CPU registers that may be used by the exception handler on the stack — except for eflags, cs, eip, ss, and esp, which have already been saved automatically by the control unit (see Section 4.2.4). The SAVE_ALL macro, which was already discussed in Section 4.6.1.4, also loads the Segment Selector of the kernel data segment in ds and es: system_call: pushl %eax SAVE_ALL movl %esp, %ebx andl $0xffffe000, %ebx The function also stores the address of the process descriptor in ebx. This is done by taking the value of the kernel stack pointer and rounding it up to a multiple of 8 KB (see Section 3.2.2). Next, the system_call( ) function checks whether the PT_TRACESYS flag included in the ptrace field of current is set — that is, whether the system call invocations of the executed program are being traced by a debugger. If this is the case, system_call( ) invokes the syscall_trace( ) function twice: once right before and once right after the execution of the system call service routine. This function stops current and thus allows the debugging process to collect information about it. A validity check is then performed on the system call number passed by the User Mode process. If it is greater than or equal to NR_syscalls, the system call handler terminates: cmpl $(NR_syscalls), %eax jb nobadsys movl $(-ENOSYS), 24(%esp) jmp ret_from_sys_call nobadsys: If the system call number is not valid, the function stores the -ENOSYS value in the stack location where the eax register has been saved (at offset 24 from the current stack top). It then jumps to ret_from_sys_call( ). In this way, when the process resumes its execution in User Mode, it will find a negative return code in eax. Finally, the specific service routine associated with the system call number contained in eax is invoked: call *sys_call_table(0, %eax, 4) Since each entry in the dispatch table is 4 bytes long, the kernel finds the address of the service routine to be invoked by multiplying the system call number by 4, adding the initial address of the sys_call_table dispatch table and extracting a pointer to the service routine from that slot in the table. When the service routine terminates, system_call( ) gets its return code from eax and stores it in the stack location where the User Mode value of the eax register is saved. It then jumps to ret_from_sys_call( ), which terminates the execution of the system call handler (see Section 4.8.3): movl %eax, 24(%esp) jmp ret_from_sys_call When the process resumes its execution in User Mode, it finds the return code of the system call in eax. 9.2.3 Parameter Passing Like ordinary functions, system calls often require some input/output parameters, which may consist of actual values (i.e., numbers), addresses of variables in the address space of the User Mode process, or even addresses of data structures including pointers to User Mode functions (see Section 10.4). Since the system_call( ) function is the common entry point for all system calls in Linux, each of them has at least one parameter: the system call number passed in the eax register. For instance, if an application program invokes the fork( ) wrapper routine, the eax register is set to 2 (i.e., _ _NR_fork) before executing the int $0x80 assembly language instruction. Because the register is set by the wrapper routines included in the libc library, programmers do not usually care about the system call number. The fork( ) system call does not require other parameters. However, many system calls do require additional parameters, which must be explicitly passed by the application program. For instance, the mmap( ) system call may require up to six additional parameters (besides the system call number). The parameters of ordinary C functions are passed by writing their values in the active program stack (either the User Mode stack or the Kernel Mode stack). Since system calls are a special kind of function that cross over from user to kernel land, neither the User Mode or the Kernel Mode stacks can be used. Rather, system call parameters are written in the CPU registers before invoking the int 0x80 assembly language instruction. The kernel then copies the parameters stored in the CPU registers onto the Kernel Mode stack before invoking the system call service routine because the latter is an ordinary C function. Why doesn't the kernel copy parameters directly from the User Mode stack to the Kernel Mode stack? First of all, working with two stacks at the same time is complex; second, the use of registers makes the structure of the system call handler similar to that of other exception handlers. However, to pass parameters in registers, two conditions must be satisfied: ● The length of each parameter cannot exceed the length of a register (32 bits).[1] [1] We refer, as usual, to the 32-bit architecture of the 80 x 86 processors. The discussion in this section does not apply to 64-bit architectures. ● The number of parameters must not exceed six (including the system call number passed in eax), since the Intel Pentium has a very limited number of registers. The first condition is always true since, according to the POSIX standard, large parameters that cannot be stored in a 32-bit register must be passed by reference. A typical example is the settimeofday( ) system call, which must read a 64-bit structure. However, system calls that have more than six parameters exist. In such cases, a single register is used to point to a memory area in the process address space that contains the parameter values. Of course, programmers do not have to care about this workaround. As with any C function call, parameters are automatically saved on the stack when the wrapper routine is invoked. This routine will find the appropriate way to pass the parameters to the kernel. The six registers used to store system call parameters are, in increasing order, eax (for the system call number), ebx, ecx, edx, esi, and edi. As seen before, system_call( ) saves the values of these registers on the Kernel Mode stack by using the SAVE_ALL macro. Therefore, when the system call service routine goes to the stack, it finds the return address to system_call( ), followed by the parameter stored in ebx (the first parameter of the system call), the parameter stored in ecx, and so on (see Section 4.6.1.4). This stack configuration is exactly the same as in an ordinary function call, and therefore the service routine can easily refer to its parameters by using the usual C-language constructs. Let's look at an example. The sys_write( ) service routine, which handles the write( ) system call, is declared as: int sys_write (unsigned int fd, const char * buf, unsigned int count) The C compiler produces an assembly language function that expects to find the fd, buf, and count parameters on top of the stack, right below the return address, in the locations used to save the contents of the ebx, ecx, and edx registers, respectively. In a few cases, even if the system call doesn't use any parameters, the corresponding service routine needs to know the contents of the CPU registers right before the system call was issued. For example, the do_fork( ) function that implements fork( ) needs to know the value of the registers in order to duplicate them in the child process thread field (see Section 3.3.2.1). In these cases, a single parameter of type pt_regs allows the service routine to access the values saved in the Kernel Mode stack by the SAVE_ALL macro (see Section 4.6.1.5): int sys_fork (struct pt_regs regs) The return value of a service routine must be written into the eax register. This is automatically done by the C compiler when a return n; instruction is executed. 9.2.4 Verifying the Parameters All system call parameters must be carefully checked before the kernel attempts to satisfy a user request. The type of check depends both on the system call and on the specific parameter. Let's go back to the write( ) system call introduced before: the fd parameter should be a file descriptor that describes a specific file, so sys_write( ) must check whether fd really is a file descriptor of a file previously opened and whether the process is allowed to write into it (see Section 1.5.6). If any of these conditions are not true, the handler must return a negative value — in this case, the error code -EBADF. One type of checking, however, is common to all system calls. Whenever a parameter specifies an address, the kernel must check whether it is inside the process address space. There are two possible ways to perform this check: ● Verify that the linear address belongs to the process address space and, if so, that the memory region including it has the proper access rights. ● Verify just that the linear address is lower than PAGE_OFFSET (i.e., that it doesn't fall within the range of interval addresses reserved to the kernel). Early Linux kernels performed the first type of checking. But it is quite time consuming since it must be executed for each address parameter included in a system call; furthermore, it is usually pointless because faulty programs are not very common. Therefore, starting with Version 2.2, Linux employs the second type of checking. This is much more efficient because it does not require any scan of the process memory region descriptors. Obviously, this is a very coarse check: verifying that the linear address is smaller than PAGE_OFFSET is a necessary but not sufficient condition for its validity. But there's no risk in confining the kernel to this limited kind of check because other errors will be caught later. The approach followed is thus to defer the real checking until the last possible moment — that is, until the Paging Unit translates the linear address into a physical one. We shall discuss in Section 9.2.6, later in this chapter, how the Page Fault exception handler succeeds in detecting those bad addresses issued in Kernel Mode that were passed as parameters by User Mode processes. One might wonder at this point why the coarse check is performed at all. This type of checking is actually crucial to preserve both process address spaces and the kernel address space from illegal accesses. We saw in Chapter 2 that the RAM is mapped starting from PAGE_OFFSET. This means that kernel routines are able to address all pages present in memory. Thus, if the coarse check were not performed, a User Mode process might pass an address belonging to the kernel address space as a parameter and then be able to read or write any page present in memory without causing a Page Fault exception. The check on addresses passed to system calls is performed by the verify_area( ) function, which acts on two parameters: addr and size.[2] [2] A third parameter named type specifies whether the system call should read or write the referred memory locations. It is used only in systems that have buggy versions of the Intel 80486 microprocessor, in which writing in Kernel Mode to a write- protected page does not generate a Page Fault. We don't discuss this case further. The function checks the address interval delimited by addr and addr + size - 1, and is essentially equivalent to the following C function: int verify_area(const void * addr, unsigned long size) { unsigned long a = (unsigned long) addr; if (a + size < a || a + size > current->addr_limit.seg) return -EFAULT; return 0; } The function first verifies whether addr + size, the highest address to be checked, is larger than 232 -1; since unsigned long integers and pointers are represented by the GNU C compiler (gcc) as 32-bit numbers, this is equivalent to checking for an overflow condition. The function also checks whether addr + size exceeds the value stored in the addr_limit.seg field of current. This field usually has the value PAGE_OFFSET for normal processes and the value 0xffffffff for kernel threads. The value of the addr_limit.seg field can be dynamically changed by the get_fs and set_fs macros; this allows the kernel to invoke system call service routines directly and to pass addresses in the kernel data segment to them. The access_ok macro performs the same check as verify_area( ). The only difference is its return value: it yields 1 if the specified address interval is valid and 0 otherwise. The _ _addr_ok macro also returns 1 if the specified linear address is valid and 0 otherwise. 9.2.5 Accessing the Process Address Space System call service routines often need to read or write data contained in the process's address space. Linux includes a set of macros that make this access easier. We'll describe two of them, called get_user( ) and put_user( ). The first can be used to read 1, 2, or 4 consecutive bytes from an address, while the second can be used to write data of those sizes into an address. Each function accepts two arguments, a value x to transfer and a variable ptr. The second variable also determines how many bytes to transfer. Thus, in get_user(x,ptr), the size of the variable pointed to by ptr causes the function to expand into a _ _get_user_1( ), _ _get_user_2( ), or _ _get_user_4( ) assembly language function. Let's consider one of them, _ _get_user_2( ): _ _ get_user_2: addl $1, %eax jc bad_get_user movl %esp, %edx andl $0xffffe000, %edx cmpl 12(%edx), %eax jae bad_get_user 2: movzwl -1(%eax), %edx xorl %eax, %eax ret bad_get_user: xorl %edx, %edx movl $-EFAULT, %eax ret The eax register contains the address ptr of the first byte to be read. The first six instructions essentially perform the same checks as the verify_area( ) functions: they ensure that the 2 bytes to be read have addresses less than 4 GB as well as less than the addr_limit.seg field of the current process. (This field is stored at offset 12 in the process descriptor, which appears in the first operand of the cmpl instruction.) If the addresses are valid, the function executes the movzwl instruction to store the data to be read in the two least significant bytes of edx register while setting the high-order bytes of edx to 0; then it sets a 0 return code in eax and terminates. If the addresses are not valid, the function clears edx, sets the -EFAULT value into eax, and terminates. The put_user(x,ptr) macro is similar to the one discussed before, except it writes the value x into the process address space starting from address ptr. Depending on the size of x, it invokes either the _ _put_user_asm( ) macro (size of 1, 2, or 4 bytes) or the _ _put_user_u64( ) macro (size of 8 bytes). Both macros return the value 0 in the eax register if they succeed in writing the value, and -EFAULT otherwise. Several other functions and macros are available to access the process address space in Kernel Mode; they are listed in Table 9-1. Notice that many of them also have a variant prefixed by two underscores (_ _ ). The ones without initial underscores take extra time to check the validity of the linear address interval requested, while the ones with the underscores bypass that check. Whenever the kernel must repeatedly access the same memory area in the process address space, it is more efficient to check the address once at the start and then access the process area without making any further checks. Table 9-1. Functions and macros that access the process address space Function Action get_user _ _get_user Reads an integer value from user space (1, 2, or 4 bytes) put_user _ _put_user Writes an integer value to user space (1, 2, or 4 bytes) copy_from_user _ _copy_from_user Copies a block of arbitrary size from user space copy_to_user _ _copy_to_user Copies a block of arbitrary size to user space strncpy_from_user _ _strncpy_from_user Copies a null-terminated string from user space strlen_user strnlen_user Returns the length of a null-terminated string in user space clear_user _ _clear_user Fills a memory area in user space with zeros 9.2.6 Dynamic Address Checking: The Fixup Code As seen previously, verify_area( ), access_ok, and _ _addr_ok make only a coarse check on the validity of linear addresses passed as parameters of a system call. Since they do not ensure that these addresses are included in the process address space, a process could cause a Page Fault exception by passing a wrong address. Before describing how the kernel detects this type of error, let's specify the three cases in which Page Fault exceptions may occur in Kernel Mode. These cases must be distinguished by the Page Fault handler, since the actions to be taken are quite different. 1. The kernel attempts to address a page belonging to the process address space, but either the corresponding page frame does not exist or the kernel tries to write a read- only page. In these cases, the handler must allocate and initialize a new page frame (see the sections Section 8.4.3 and Section 8.4.4). 2. The kernel addresses a page belonging to its address space, but the corresponding Page Table entry has not yet been initialized (see Section 8.4.5). In this case, the kernel must properly set up some entries in the Page Tables of the current process. 3. Some kernel function includes a programming bug that causes the exception to be raised when that program is executed; alternatively, the exception might be caused by a transient hardware error. When this occurs, the handler must perform a kernel oops (see Section 8.4.1). 4. The case introduced in this chapter: a system call service routine attempts to read or write into a memory area whose address has been passed as a system call parameter, but that address does not belong to the process address space. The Page Fault handler can easily recognize the first case by determining whether the faulty linear address is included in one of the memory regions owned by the process. It is also able to detect the second case by checking whether the Page Tables of the process include a proper non-null entry that maps the address. Let's now explain how the handler distinguishes the remaining two cases. 9.2.6.1 The exception tables The key to determining the source of a Page Fault lies in the narrow range of calls that the kernel uses to access the process address space. Only the small group of functions and macros described in the previous section are used to access this address space; thus, if the exception is caused by an invalid parameter, the instruction that caused it must be included in one of the functions, or else be generated by expanding one of the macros. The number of the instructions that address user space is fairly small. Therefore, it does not take much effort to put the address of each kernel instruction that accesses the process address space into a structure called the exception table. If we succeed in doing this, the rest is easy. When a Page Fault exception occurs in Kernel Mode, the do_ page_fault( ) handler examines the exception table: if it includes the address of the instruction that triggered the exception, the error is caused by a bad system call parameter; otherwise, it is caused by a more serious bug. Linux defines several exception tables. The main exception table is automatically generated by the C compiler when building the kernel program image. It is stored in the _ _ex_table section of the kernel code segment, and its starting and ending addresses are identified by two symbols produced by the C compiler: _ _start_ _ _ex_table and _ _stop_ _ _ex_table. Moreover, each dynamically loaded module of the kernel (see Appendix B) includes its own local exception table. This table is automatically generated by the C compiler when building the module image, and it is loaded into memory when the module is inserted in the running kernel. Each entry of an exception table is an exception_table_entry structure that has two fields: insn The linear address of an instruction that accesses the process address space fixup The address of the assembly language code to be invoked when a Page Fault exception triggered by the instruction located at insn occurs The fixup code consists of a few assembly language instructions that solve the problem triggered by the exception. As we shall see later in this section, the fix usually consists of inserting a sequence of instructions that forces the service routine to return an error code to the User Mode process. Such instructions are usually defined in the same macro or function that accesses the process address space; sometimes they are placed by the C compiler into a separate section of the kernel code segment called .fixup. The search_exception_table( ) function is used to search for a specified address in all exception tables: if the address is included in a table, the function returns the corresponding fixup address; otherwise, it returns 0. Thus the Page Fault handler do_page_fault( ) executes the following statements: if ((fixup = search_exception_table(regs->eip)) != 0) { regs->eip = fixup; return; } The regs->eip field contains the value of the eip register saved on the Kernel Mode stack when the exception occurred. If the value in the register (the instruction pointer) is in an exception table, do_page_fault( ) replaces the saved value with the address returned by search_exception_table( ). Then the Page Fault handler terminates and the interrupted program resumes with execution of the fixup code. 9.2.6.2 Generating the exception tables and the fixup code The GNU Assembler .section directive allows programmers to specify which section of the executable file contains the code that follows. As we shall see in Chapter 20, an executable file includes a code segment, which in turn may be subdivided into sections. Thus, the following assembly language instructions add an entry into an exception table; the "a" attribute specifies that the section must be loaded into memory together with the rest of the kernel image: .section _ _ex_table, "a" .long faulty_instruction_address, fixup_code_address .previous The .previous directive forces the assembler to insert the code that follows into the section that was active when the last .section directive was encountered. Let's consider again the _ _get_user_1( ), _ _get_user_2( ), and _ _get_user_4( ) functions mentioned before. The instructions that access the process address space are those labeled as 1, 2, and 3: _ _get_user_1: [...] 1: movzbl (%eax), %edx [...] _ _get_user_2: [...] 2: movzwl -1(%eax), %edx [...] _ _get_user_4: [...] 3: movl -3(%eax), %edx [...] bad_get_user: xorl %edx, %edx movl $-EFAULT, %eax ret .section _ _ex_table,"a" .long 1b, bad_get_user .long 2b, bad_get_user .long 3b, bad_get_user .previous Each exception table entry consists of two labels. The first one is a numeric label with a b suffix to indicate that the label is "backward"; in other words, it appears in a previous line of the program. The fixup code is common to the three functions and is labeled as bad_get_user. If a Page Fault exception is generated by the instructions at label 1, 2, or 3, the fixup code is executed. It simply returns an -EFAULT error code to the process that issued the system call. Other kernel functions that act in the User Mode address space use the fixup code technique. Consider, for instance, the strlen_user(string) macro. This macro returns either the length of a null-terminated string passed as a parameter in a system call or the value 0 on error. The macro essentially yields the following assembly language instructions: movl $0, %eax movl $0x7fffffff, %ecx movl %ecx, %ebp movl string, %edi 0: repne; scasb subl %ecx, %ebp movl %ebp, %eax 1: .section .fixup,"ax" 2: movl $0, %eax jmp 1b .previous .section _ _ex_table,"a" .long 0b, 2b .previous The ecx and ebp registers are initialized with the 0x7fffffff value, which represents the maximum allowed length for the string in the User Mode address space. The repne;scasb assembly language instructions iteratively scan the string pointed to by the edi register, looking for the value 0 (the end of string \0 character) in eax. Since scasb decrements the ecx register at each iteration, the eax register ultimately stores the total number of bytes scanned in the string (that is, the length of the string). The fixup code of the macro is inserted into the .fixup section. The "ax" attributes specify that the section must be loaded into memory and that it contains executable code. If a Page Fault exception is generated by the instructions at label 0, the fixup code is executed; it simply loads the value 0 in eax — thus forcing the macro to return a 0 error code instead of the string length — and then jumps to the 1 label, which corresponds to the instruction following the macro. I l@ve RuBoard I l@ve RuBoard 9.3 Kernel Wrapper Routines Although system calls are used mainly by User Mode processes, they can also be invoked by kernel threads, which cannot use library functions. To simplify the declarations of the corresponding wrapper routines, Linux defines a set of seven macros called _syscall0 through _syscall6. In the name of each macro, the numbers 0 through 6 correspond to the number of parameters used by the system call (excluding the system call number). The macros are used to declare wrapper routines that are not already included in the libc standard library (for instance, because the Linux system call is not yet supported by the library); however, they cannot be used to define wrapper routines for system calls that have more than six parameters (excluding the system call number) or for system calls that yield nonstandard return values. Each macro requires exactly 2+2xn parameters, with n being the number of parameters of the system call. The first two parameters specify the return type and the name of the system call; each additional pair of parameters specifies the type and the name of the corresponding system call parameter. Thus, for instance, the wrapper routine of the fork( ) system call may be generated by: _syscall0(int,fork) while the wrapper routine of the write( ) system call may be generated by: _syscall3(int,write,int,fd,const char *,buf,unsigned int,count) In the latter case, the macro yields the following code: int write(int fd,const char * buf,unsigned int count) { long _ _res; asm("int $0x80" : "=a" (_ _res) : "0" (_ _NR_write), "b" ((long)fd), "c" ((long)buf), "d" ((long)count)); if ((unsigned long)_ _res >= (unsigned long)-125) { errno = -_ _res; _ _res = -1; } return (int) _ _res; } The _ _NR_write macro is derived from the second parameter of _syscall3; it expands into the system call number of write( ). When compiling the preceding function, the following assembly language code is produced: write: pushl %ebx ; push ebx into stack movl 8(%esp), %ebx ; put first parameter in ebx movl 12(%esp), %ecx ; put second parameter in ecx movl 16(%esp), %edx ; put third parameter in edx movl $4, %eax ; put _ _NR_write in eax int $0x80 ; invoke system call cmpl $-126, %eax ; check return code jbe .L1 ; if no error, jump negl %eax ; complement the value of eax movl %eax, errno ; put result in errno movl $-1, %eax ; set eax to -1 .L1: popl %ebx ; pop ebx from stack ret ; return to calling program Notice how the parameters of the write( ) function are loaded into the CPU registers before the int $0x80 instruction is executed. The value returned in eax must be interpreted as an error code if it lies between -1 and -125 (the kernel assumes that the largest error code defined in include/asm-i386/errno.h is 125). If this is the case, the wrapper routine stores the value of -eax in errno and returns the value -1; otherwise, it returns the value of eax. I l@ve RuBoard I l@ve RuBoard Chapter 10. Signals Signals were introduced by the first Unix systems to allow interactions between User Mode processes; the kernel also uses them to notify processes of system events. Signals have been around for 30 years with only minor changes. The first sections of this chapter examine in detail how signals are handled by the Linux kernel, then we discuss the system calls that allow processes to exchange signals. I l@ve RuBoard I l@ve RuBoard 10.1 The Role of Signals A signal is a very short message that may be sent to a process or a group of processes. The only information given to the process is usually a number identifying the signal; there is no room in standard signals for arguments, a message, or other accompanying information. A set of macros whose names start with the prefix SIG is used to identify signals; we have already made a few references to them in previous chapters. For instance, the SIGCHLD macro was mentioned in Section 3.4.1. This macro, which expands into the value 17 in Linux, yields the identifier of the signal that is sent to a parent process when a child stops or terminates. The SIGSEGV macro, which expands into the value 11, was mentioned in Section 8.4 ; it yields the identifier of the signal that is sent to a process when it makes an invalid memory reference. Signals serve two main purposes: ● To make a process aware that a specific event has occurred ● To force a process to execute a signal handler function included in its code Of course, the two purposes are not mutually exclusive, since often a process must react to some event by executing a specific routine. Table 10-1 lists the first 31 signals handled by Linux 2.4 for the 80 x 86 architecture (some signal numbers, such those associated with SIGCHLD or SIGSTOP, are architecture-dependent; furthermore, some signals such as SIGSTKFLT are defined only for specific architectures). The meanings of the default actions are described in the next section. Table 10-1. The first 31 signals in Linux/i386 # Signal name Default action Comment POSIX 1 SIGHUP Terminate Hang up controlling terminal or process Yes 2 SIGINT Terminate Interrupt from keyboard Yes 3 SIGQUIT Dump Quit from keyboard Yes 4 SIGILL Dump Illegal instruction Yes 5 SIGTRAP Dump Breakpoint for debugging No 6 SIGABRT Dump Abnormal termination Yes 6 SIGIOT Dump Equivalent to SIGABRT No 7 SIGBUS Dump Bus error No 8 SIGFPE Dump Floating-point exception Yes 9 SIGKILL Terminate Forced-process termination Yes 10 SIGUSR1 Terminate Available to processes Yes 11 SIGSEGV Dump Invalid memory reference Yes 12 SIGUSR2 Terminate Available to processes Yes 13 SIGPIPE Terminate Write to pipe with no readers Yes 14 SIGALRM Terminate Real-timer clock Yes 15 SIGTERM Terminate Process termination Yes 16 SIGSTKFLT Terminate Coprocessor stack error No 17 SIGCHLD Ignore Child process stopped or terminated Yes 18 SIGCONT Continue Resume execution, if stopped Yes 19 SIGSTOP Stop Stop process execution Yes 20 SIGTSTP Stop Stop process issued from tty Yes 21 SIGTTIN Stop Background process requires input Yes 22 SIGTTOU Stop Background process requires output Yes 23 SIGURG Ignore Urgent condition on socket No 24 SIGXCPU Dump CPU time limit exceeded No 25 SIGXFSZ Dump File size limit exceeded No 26 SIGVTALRM Terminate Virtual timer clock No 27 SIGPROF Terminate Profile timer clock No 28 SIGWINCH Ignore Window resizing No 29 SIGIO Terminate I/O now possible No 29 SIGPOLL Terminate Equivalent to SIGIO No 30 SIGPWR Terminate Power supply failure No 31 SIGSYS Dump Bad system call No 31 SIGUNUSED Dump Equivalent to SIGSYS No Besides the regular signals described in this table, the POSIX standard has introduced a new class of signals denoted as real-time signals; their signal numbers range from 32 to 63 on Linux. They mainly differ from regular signals because they are always queued so that multiple signals sent will be received. On the other hand, regular signals of the same kind are not queued: if a regular signal is sent many times in a row, just one of them is delivered to the receiving process. Although the Linux kernel does not use real-time signals, it fully supports the POSIX standard by means of several specific system calls. A number of system calls allow programmers to send signals and determine how their processes respond to the signals they receive. Table 10-2 summarizes these calls; their behavior is described in detail in the later section Section 10.4. Table 10-2. The most significant system calls related to signals System call Description kill( ) Send a signal to a process. sigaction( ) Change the action associated with a signal. signal( ) Similar to sigaction( ). sigpending( ) Check whether there are pending signals. sigprocmask( ) Modify the set of blocked signals. sigsuspend( ) Wait for a signal. rt_sigaction( ) Change the action associated with a real-time signal. rt_sigpending( ) Check whether there are pending real-time signals. rt_sigprocmask( ) Modify the set of blocked real-time signals. rt_sigqueueinfo( ) Send a real-time signal to a process. rt_sigsuspend( ) Wait for a real-time signal. rt_sigtimedwait( ) Similar to rt_sigsuspend( ). An important characteristic of signals is that they may be sent at any time to a process whose state is usually unpredictable. Signals sent to a process that is not currently executing must be saved by the kernel until that process resumes execution. Blocking a signal (described later) requires that delivery of the signal be held off until it is later unblocked, which exacerbates the problem of signals being raised before they can be delivered. Therefore, the kernel distinguishes two different phases related to signal transmission: Signal generation The kernel updates a data structure of the destination process to represent that a new signal has been sent. Signal delivery The kernel forces the destination process to react to the signal by changing its execution state, by starting the execution of a specified signal handler, or both. Each signal generated can be delivered once, at most. Signals are consumable resources: once they have been delivered, all process descriptor information that refers to their previous existence is canceled. Signals that have been generated but not yet delivered are called pending signals. At any time, only one pending signal of a given type may exist for a process; additional pending signals of the same type to the same process are not queued but simply discarded. Real-time signals are different, though: there can be several pending signals of the same type. In general, a signal may remain pending for an unpredictable amount of time. The following factors must be taken into consideration: ● Signals are usually delivered only to the currently running process (that is, by the current process). ● Signals of a given type may be selectively blocked by a process (see the later section Section 10.4.4). In this case, the process does not receive the signal until it removes the block. ● When a process executes a signal-handler function, it usually masks the corresponding signal—i.e., it automatically blocks the signal until the handler terminates. A signal handler therefore cannot be interrupted by another occurrence of the handled signal and the function doesn't need to be re-entrant. Although the notion of signals is intuitive, the kernel implementation is rather complex. The kernel must: ● Remember which signals are blocked by each process. ● When switching from Kernel Mode to User Mode, check whether a signal for any process has arrived. This happens at almost every timer interrupt (roughly every 10 ms). ● Determine whether the signal can be ignored. This happens when all of the following conditions are fulfilled: ❍ The destination process is not traced by another process (the PT_PTRACED flag in the process descriptor ptrace field is equal to 0).[1] [1] If a process receives a signal while it is being traced, the kernel stops the process and notifies the tracing process by sending a SIGCHLD signal to it. The tracing process may, in turn, resume execution of the traced process by means of a SIGCONT signal. ● The signal is not blocked by the destination process. ● The signal is being ignored by the destination process (either because the process explicitly ignored it or because the process did not change the default action of the signal and that action is "ignore"). ● Handle the signal, which may require switching the process to a handler function at any point during its execution and restoring the original execution context after the function returns. Moreover, Linux must take into account the different semantics for signals adopted by BSD and System V; furthermore, it must comply with the rather cumbersome POSIX requirements. 10.1.1 Actions Performed upon Delivering a Signal There are three ways in which a process can respond to a signal: 1. Explicitly ignore the signal. 2. Execute the default action associated with the signal (see Table 10-1). This action, which is predefined by the kernel, depends on the signal type and may be any one of the following: Terminate The process is terminated (killed). Dump The process is terminated (killed) and a core file containing its execution context is created, if possible; this file may be used for debug purposes. Ignore The signal is ignored. Stop The process is stopped—i.e., put in the TASK_STOPPED state (see Section 3.2.1). Continue If the process is stopped (TASK_STOPPED), it is put into the TASK_RUNNING state. 3. Catch the signal by invoking a corresponding signal-handler function. Notice that blocking a signal is different from ignoring it. A signal is not delivered as long as it is blocked; it is delivered only after it has been unblocked. An ignored signal is always delivered, and there is no further action. The SIGKILL and SIGSTOP signals cannot be ignored, caught, or blocked, and their default actions must always be executed. Therefore, SIGKILL and SIGSTOP allow a user with appropriate privileges to terminate and to stop, respectively, any process,[2] regardless of the defenses taken by the program it is executing. [2] There are two exceptions: it is not possible to send a signal to process 0 (swapper), and signals sent to process 1 (init) are always discarded unless they are caught. Therefore, process 0 never dies, while process 1 dies only when the init program terminates. 10.1.2 Data Structures Associated with Signals For any process in the system, the kernel must keep track of what signals are currently pending or masked, as well as how to handle every signal. To do this, it uses several data structures accessible from the processor descriptor. The most significant ones are shown in Figure 10-1. Figure 10-1. The most significant data structures related to signal handling The fields of the process descriptor related to signal handling are listed in Table 10-3. Table 10-3. Process descriptor fields related to signal handling Type Name Description spinlock_t sigmask_lock Spin lock protecting pending and blocked struct signal_struct * sig Pointer to the process's signal descriptor sigset_t blocked Mask of blocked signals struct sigpending pending Data structure storing the pending signals unsigned long sas_ss_sp Address of alternate signal handler stack size_t sas_ss_size Size of alternate signal handler stack int (*) (void *) notifier Pointer to a function used by a device driver to block some signals of the process void * notifier_data Pointer to data that might be used by the notifier function (previous field of table) sigset_t * notifier_mask Bit mask of signals blocked by a device driver through a notifier function The blocked field stores the signals currently masked out by the process. It is a sigset_t array of bits, one for each signal type: typedef struct { unsigned long sig[2]; } sigset_t; Since each unsigned long number consists of 32 bits, the maximum number of signals that may be declared in Linux is 64 (the _NSIG macro specifies this value). No signal can have number 0, so the signal number corresponds to the index of the corresponding bit in a sigset_t variable plus one. Numbers between 1 and 31 correspond to the signals listed in Table 10-1, while numbers between 32 and 64 correspond to real-time signals. The sig field of the process descriptor points to a signal descriptor, which describes how each signal must be handled by the process. The descriptor is stored in a signal_struct structure, which is defined as follows: struct signal_struct { atomic_t count; struct k_sigaction action[64]; spinlock_t siglock; }; As mentioned in Section 3.4.1, this structure may be shared by several processes by invoking the clone( ) system call with the CLONE_SIGHAND flag set.[3] The count field specifies the number of processes that share the signal_struct structure, while the siglock field is used to ensure exclusive access to its fields. The action field is an array of 64 k_sigaction structures that specify how each signal must be handled. [3] If this is not done, about 1,300 bytes are added to the process data structures just to take care of signal handling. Some architectures assign properties to a signal that are visible only to the kernel. Thus, the properties of a signal are stored in a k_sigaction structure, which contains both the properties hidden from the User Mode process and the more familiar sigaction structure that holds all the properties a User Mode process can see. Actually, on the 80 x 86 platform, all signal properties are visible to User Mode processes. Thus the k_sigaction structure simply reduces to a single sa structure of type sigaction, which includes the following fields: sa_handler or sa_sigaction Both names refer to the same field of the structure, which specifies the type of action to be performed; its value can be either a pointer to the signal handler, SIG_DFL (that is, the value 0) to specify that the default action is performed, or SIG_IGN (that is, the value 1) to specify that the signal is ignored. The two different names of this field corresponds to two different types of signal handler (see Section 10.4.2 later in this chapter). sa_flags This set of flags specifies how the signal must be handled; some of them are listed in Table 10-4. sa_mask This sigset_t variable specifies the signals to be masked when running the signal handler. Table 10-4. Flags specifying how to handle a signal Flag Name Description SA_NOCLDSTOP Do not send SIGCHLD to the parent when the process is stopped. SA_NODEFER, SA_NOMASK Do not mask the signal while executing the signal handler. SA_RESETHAND, SA_ONESHOT Reset to default action after executing the signal handler. SA_ONSTACK Use an alternate stack for the signal handler (see the later section Section 10.3.3). SA_RESTART Interrupted system calls are automatically restarted (see the later section Section 10.3.4). SA_SIGINFO Provide additional information to the signal handler (see the later section Section 10.4.2). The pending field of the process descriptor is used to keep track of what signals are currently pending. It consists of a struct sigpending data structure, which is defined as follows: struct sigpending { struct sigqueue * head, ** tail; sigset_t signal; } The signal field is a bit mask specifying the pending signals for the process, while the head and tail fields point to the first and last items of a pending signal queue. This queue is implemented through a list of struct sigqueue data structures: struct sigqueue { struct sigqueue * next; siginfo_t info; } The nr_queued_signals variable stores the number of items in the queue, while the max_queued_signals defines the maximum length of the queue (which is 1,024 by default, but the system administrator can change this value either by writing into the /proc/sys/kernel/rtsig-max file or by issuing a suitable sysctl( ) system call). The siginfo_t data structure is a 128-byte data structure that stores information about an occurrence of a specific signal; it includes the following fields: si_signo The signal number. si_errno The error code of the instruction that caused the signal to be raised, or 0 if there was no error. si_code A code identifying who raised the signal (see Table 10-5). Table 10-5. The most significant signal sender codes Code Name Sender SI_USER kill( ) and raise( ) (see the later section Section 10.4) SI_KERNEL Generic kernel function SI_TIMER Timer expiration SI_ASYNCIO Asynchronous I/O completion _sifields A union storing information depending on the type of signal. For instance, the siginfo_t data structure relative to an occurrence of the SIGKILL signal records the PID and the UID of the sender process here; conversely, the data structure relative to an occurrence of the SIGSEGV signal stores the memory address whose access caused the signal to be raised. 10.1.3 Operations on Signal Data Structures Several functions and macros are used by the kernel to handle signals. In the following description, set is a pointer to a sigset_t variable, nsig is the number of a signal, and mask is an unsigned long bit mask. sigemptyset(set) and sigfillset(set) Sets the bits in the sigset_t variable to 0 or 1, respectively. sigaddset(set,nsig) and sigdelset(set,nsig) Sets the bit of the sigset_t variable corresponding to signal nsig to 1 or 0, respectively. In practice, sigaddset( ) reduces to: set->sig[(nsig - 1) / 32] |= 1UL << ((nsig - 1) % 32); and sigdelset( ) to: set->sig[(nsig - 1) / 32] &= ~(1UL << ((nsig - 1) % 32)); sigaddsetmask(set,mask) and sigdelsetmask(set,mask) Sets all the bits of the sigset_t variable whose corresponding bits of mask are on 1 or 0, respectively. They can be used only with signals that are between 1 and 32. The corresponding functions reduce to: set->sig[0] |= mask; and to: set->sig[0] &= ~mask; sigismember(set,nsig) Returns the value of the bit of the sigset_t variable corresponding to the signal nsig. In practice, this function reduces to: return 1 & (set->sig[(nsig-1) / 32] >> ((nsig-1) % 32)); sigmask(nsig) Yields the bit index of the signal nsig. In other words, if the kernel needs to set, clear, or test a bit in an element of sigset_t that corresponds to a particular signal, it can derive the proper bit through this macro. sigandsets(d,s1,s2), sigorsets(d,s1,s2), and signandsets(d,s1,s2) Performs a logical AND, a logical OR, and a logical NAND, respectively, between the sigset_t variables to which s1 and s2 point; the result is stored in the sigset_t variable to which d points. sigtestsetmask(set,mask) Returns the value 1 if any of the bits in the sigset_t variable that correspond to the bits set to 1 in mask is set; it returns 0 otherwise. It can be used only with signals that have a number between 1 and 32. siginitset(set,mask) Initializes the low bits of the sigset_t variable corresponding to signals between 1 and 32 with the bits contained in mask, and clears the bits corresponding to signals between 33 and 63. siginitsetinv(set,mask) Initializes the low bits of the sigset_t variable corresponding to signals between 1 and 32 with the complement of the bits contained in mask, and sets the bits corresponding to signals between 33 and 63. signal_pending(p) Returns the value 1 (true) if the process identified by the *p process descriptor has nonblocked pending signals, and returns the value 0 (false) if it doesn't. The function is implemented as a simple check on the sigpending field of the process descriptor. recalc_sigpending(t) Checks whether the process identified by the process descriptor at *t has nonblocked pending signals by looking at the sig and blocked fields of the process, and then sets the sigpending field to or 1 as follows: ready = t->pending.signal.sig[1] & ~t->blocked.sig[1]; ready |= t->pending.signal.sig[0] & ~t->blocked.sig[0]; t->sigpending = (ready != 0); flush_signals(t) Deletes all signals sent to the process identified by the process descriptor at *t. This is done by clearing both the t->sigpending and the t->pending.signal fields and by emptying the queue of pending signals. I l@ve RuBoard I l@ve RuBoard 10.2 Generating a Signal When a signal is sent to a process, either from the kernel or from another process, the kernel generates it by invoking the send_sig_info( ), send_sig( ), force_sig( ), or force_sig_info( ) functions. These accomplish the first phase of signal handling described earlier in Section 10.1, updating the process descriptor as needed. They do not directly perform the second phase of delivering the signal but, depending on the type of signal and the state of the process, may wake up the process and force it to receive the signal. 10.2.1 The send_sig_info( ) and send_sig( ) Functions The send_sig_info( ) function acts on three parameters: sig The signal number. info Either the address of a siginfo_t table or one of two special values. 0 means that the signal has been sent by a User Mode process, while 1 means that it has been sent by the kernel. t A pointer to the descriptor of the destination process. The send_sig_info( ) function starts by checking whether the parameters are correct: if (sig < 0 || sig > 64) return -EINVAL; The function then checks if the signal is being sent by a User Mode process. This occurs when info is equal to 0 or when the si_code field of the siginfo_t table is negative or 0 (positive values of this field mean that the signal was sent by some kernel function): if ((!info || ((unsigned long)info != 1 && (info->si_code <=0))) && ((sig != SIGCONT) || (current->session != t->session)) && (current->euid ^ t->suid) && (current->euid ^ t->uid) && (current->uid ^ t->suid) && (current->uid ^ t->uid) && !capable(CAP_KILL)) return -EPERM; If the signal is sent by a User Mode process, the function determines whether the operation is allowed. The signal is delivered only if at least one of the following conditions holds: ● The owner of the sending process has the proper capability (usually, this simply means the signal was issued by the system administrator; see Chapter 20). ● The signal is SIGCONT and the destination process is in the same login session of the sending process. ● Both processes belong to the same user. If the sig parameter has the value 0, the function returns immediately without generating any signal. Since 0 is not a valid signal number, it is used to allow the sending process to check whether it has the required privileges to send a signal to the destination process. The function also returns if the destination process is in the TASK_ZOMBIE state, indicated by checking whether its siginfo_t table has been released: if (!sig || !t->sig) return 0; Now the kernel has finished the preliminary checks, and it is going to fiddle with the signal-related data structures. To avoid race conditions, it disables the interrupts and acquires the signal spin lock of the destination process: spin_lock_irqsave(&t->sigmask_lock, flags); Some types of signals might nullify other pending signals for the destination process. Therefore, the function checks whether one of the following cases occurs: ● sig is a SIGKILL or SIGCONT signal. If the destination process is stopped, it is put in the TASK_RUNNING state so that it is able to either execute the do_exit( ) function or just continue its execution; moreover, if the destination process has SIGSTOP, SIGTSTP, SIGTTOU, or SIGTTIN pending signals, they are removed: if (t->state == TASK_STOPPED) wake_up_process(t); t->exit_code = 0; rm_sig_from_queue(SIGSTOP, t); rm_sig_from_queue(SIGTSTP, t); rm_sig_from_queue(SIGTTOU, t); rm_sig_from_queue(SIGTTIN, t); The rm_sig_from_queue( ) function clears the bit in t->pending.signal associated with the signal number passed as first argument and removes any item in the pending signal queue of the process that corresponds to that signal number. ● sig is a SIGSTOP, SIGTSTP, SIGTTIN, or SIGTTOU signal. If the destination process has a pending SIGCONT signal, it is removed: rm_sig_from_queue(SIGCONT, t); Next, send_sig_info( ) checks whether the new signal can be handled immediately. In this case, the function also takes care of the delivering phase of the signal: if (ignored_signal(sig, t)) { spin_unlock_irqrestore(&t->sigmask_lock, flags); return 0; } The ignored_signal( ) function returns the value 1 when all three conditions for ignoring a signal that are mentioned in Section 10.1 are satisfied. However, to fulfill a POSIX requirement, the SIGCHLD signal is handled specially. POSIX distinguishes between explicitly setting the "ignore" action for the SIGCHLD signal and leaving the default in place (even if the default is to ignore the signal). To let the kernel clean up a terminated child process and prevent it from becoming a zombie (see Section 3.5.2), the parent must explicitly set the action to "ignore" the signal. So ignored_signal( ) handles this case as follows: if the signal is explicitly ignored, ignored_signal( ) returns 0, but if the default action was "ignore" and the process didn't change that default, ignored_signal( ) returns 1. If ignored_signal( ) returns 1, the siginfo_t table of the destination process must not be updated, and the send_sig_info( ) function terminates. Since the signal is no longer pending, it has been effectively delivered to the destination process, even if the process never sees it. If ignored_signal( ) returns 0, the phase of signal delivering has to be deferred, therefore send_sig_info( ) may have to modify the data structures of the destination process to let it know later that a new signal has been sent to it. However, if the signal being handled was already pending, the send_sig_info( ) function can simply terminate. In fact, there can be at most one occurrence of any regular signal type in the pending signal queue of a process because regular signal occurrences are not really queued: if (sig < 32 && sigismember(&t->pending.signal, sig)) { spin_unlock_irqrestore(&t->sigmask_lock, flags); return 0; } If it proceeds, the send_sig_info( ) function must insert a new item in the pending signal queue of the destination process. This is achieved by invoking the send_signal( ) function: retval = send_signal(sig, info, &t->pending); In turn, the send_signal( ) function checks the length of the pending signal queue and appends a new sigqueue data structure: if (atomic_read(&nr_queued_signals) < max_queued_signals) { q = kmem_cache_alloc(sigqueue_cachep, GFP_ATOMIC); atomic_inc(&nr_queued_signals); q->next = NULL; *(t->pending.tail) = q; t->pending.tail = &q->next; Then the send_sig_info( ) function fills the siginfo_t table inside the new queue item: if ((unsigned long)info == 0) { q->info.si_signo = sig; q->info.si_errno = 0; q->info.si_code = SI_USER; q->info._sifields._kill._pid = current->pid; q->info._sifields._kill._uid = current->uid; } else if ((unsigned long)info == 1) { q->info.si_signo = sig; q->info.si_errno = 0; q->info.si_code = SI_KERNEL; q->info._sifields._kill._pid = 0; q->info._sifields._kill._uid = 0; } else copy_siginfo(&q->info, info); } The info argument passed to the send_signal( ) function either points to a previously built siginfo_t table or stores the constants 0 (for a signal sent by a User Mode process) or 1 (for a signal sent by a kernel function). If it is not possible to add an item to the queue, either because it already includes max_queued_signals elements or because there is no free memory for the sigqueue data structure, the signal occurrence cannot be queued. If the signal is real-time and was sent through a system call that is explicitly required to queue it (like rt_sigqueueinfo( )), the send_signal( ) function returns an error code. Otherwise, it sets the corresponding bit in t->pending.signal: if (sig >= 32 && info && (unsigned long)info != 1 && info->si_code != SI_USER) return -EAGAIN; sigaddset(&t->pending.signal, sig); return 0; It is important to let the destination process receive the signal even if there is no room for the corresponding item in the pending signal queue. Suppose, for instance, that a process is consuming too much memory. The kernel must ensure that the kill( ) system call succeeds even if there is no free memory; otherwise, the system administrator doesn't have any chance to recover the system by terminating the offending process. If the send_signal( ) function successfully terminated and the signal is not blocked, the destination process has a new pending signal to consider: if (!retval && !sigismember(&t->blocked, sig)) signal_wake_up(t); The signal_wake_up( ) function performs three actions: 1. Sets the sigpending flag of the destination process. 2. Checks whether the destination process is already running on another CPU and, in this case, sends an interprocessor interrupt to that CPU to force a reschedule of the current process (see Section 4.6.2). Since each process checks the existence of pending signals when returning from the schedule( ) function, the interprocessor interrupt ensures that the destination process quickly notices the new pending signal if it is already running. 3. Checks whether the destination process is in the TASK_INTERRUPTIBLE state and, in this case, wakes it up by invoking the wake_up_process( ). Finally, the send_sig_info( ) function re-enables the interrupts, releases the spin lock, and terminates with the error code of send_signal( ): spin_unlock_irqrestore(&t->sigmask_lock, flags); return retval; The send_sig( ) function is similar to send_sig_info( ). However, the info parameter is replaced by a priv flag, which is 1 if the signal is sent by the kernel and 0 if it is sent by a process. The send_sig( ) function is implemented as a special case of send_sig_info( ): return send_sig_info(sig, (void*)(long)(priv != 0), t); 10.2.2 The force_sig_info( ) and force_sig( ) Functions The force_sig_info(sig, info, t) function is used by the kernel to send signals that cannot be explicitly ignored or blocked by the destination processes. The function's parameters are the same as those of send_sig_info( ). The force_sig_info( ) function acts on the signal_struct data structure that is referenced by the sig field included in the descriptor t of the destination process: spin_lock_irqsave(&t->sigmask_lock, flags); if (t->sig->action[sig-1].sa.sa_handler == SIG_IGN) t->sig->action[sig-1].sa.sa_handler = SIG_DFL; sigdelset(&t->blocked, sig); recalc_sigpending(t); spin_unlock_irqrestore(&t->sigmask_lock, flags); return send_sig_info(sig, info, t); force_sig( ) is similar to force_sig_info( ). Its use is limited to signals sent by the kernel; it can be implemented as a special case of the force_sig_info( ) function: force_sig_info(sig, (void*)1L, t); I l@ve RuBoard I l@ve RuBoard 10.3 Delivering a Signal We assume that the kernel noticed the arrival of a signal and invoked one of the functions mentioned in the previous section to prepare the process descriptor of the process that is supposed to receive the signal. But in case that process was not running on the CPU at that moment, the kernel deferred the task of delivering the signal. We now turn to the activities that the kernel performs to ensure that pending signals of a process are handled. As mentioned in Section 4.8, the kernel checks the value of the sigpending flag of the process descriptor before allowing the process to resume its execution in User Mode. Thus, the kernel checks for the existence of pending signals every time it finishes handling an interrupt or an exception. To handle the nonblocked pending signals, the kernel invokes the do_signal( ) function, which receives two parameters: regs The address of the stack area where the User Mode register contents of the current process are saved. oldset The address of a variable where the function is supposed to save the bit mask array of blocked signals. It is NULL if there is no need to save the bit mask array. The do_signal( ) function starts by checking whether the function itself was triggered by an interrupt; if so, it simply returns. Otherwise, if the function was triggered by an exception that was raised while the process was running in User Mode, the function continues executing: if ((regs->xcs & 3) != 3) return 1; However, as we'll see in Section 10.3.4, this does not mean that a system call cannot be interrupted by a signal. If the oldset parameter is NULL, the function initializes it with the address of the current- >blocked field: if (!oldset) oldset = ¤t->blocked; The heart of the do_signal( ) function consists of a loop that repeatedly invokes the dequeue_signal( ) function until no nonblocked pending signals are left. The return code of dequeue_signal( ) is stored in the signr local variable. If its value is 0, it means that all pending signals have been handled and do_signal( ) can finish. As long as a nonzero value is returned, a pending signal is waiting to be handled. dequeue_signal( ) is invoked again after do_signal( ) handles the current signal. The dequeue_signal( ) always considers the lowest-numbered pending signal. It updates the data structures to indicate that the signal is no longer pending and returns its number. This task involves clearing the corresponding bit in current->pending.signal and updating the value of current->sigpending. In the mask parameter, each bit that is set represents a blocked signal: sig = 0; if (((x = current->pending.signal.sig[0]) & ~mask->sig[0]) != 0) sig = 1 + ffz(~x); else if (((x = current->pending.signal.sig[1]) & ~mask->sig[1]) != 0) sig = 33 + ffz(~x); if (sig) { sigdelset(¤t->signal, sig); recalc_sigpending(current); } return sig; The collection of currently pending signals is ANDed with the blocked signals (the complement of mask). If anything is left, it represents a signal that should be delivered to the process. The ffz( ) function returns the index of the first bit in its parameter; this value is used to compute the lowest-number signal to be delivered. Let's see how the do_signal( ) function handles any pending signal whose number is returned by dequeue_signal( ). First, it checks whether the current receiver process is being monitored by some other process; in this case, do_signal( ) invokes notify_parent( ) and schedule( ) to make the monitoring process aware of the signal handling. Then do_signal( ) loads the ka local variable with the address of the k_sigaction data structure of the signal to be handled: ka = ¤t->sig->action[signr-1]; Depending on the contents, three kinds of actions may be performed: ignoring the signal, executing a default action, or executing a signal handler. 10.3.1 Ignoring the Signal When a delivered signal is explicitly ignored, the do_signal( ) function normally just continues with a new execution of the loop and therefore considers another pending signal. One exception exists, as described earlier: if (ka->sa.sa_handler == SIG_IGN) { if (signr == SIGCHLD) while (sys_wait4(-1, NULL, WNOHANG, NULL) > 0) /* nothing */; continue; } If the signal delivered is SIGCHLD, the sys_wait4( ) service routine of the wait4( ) system call is invoked to force the process to read information about its children, thus cleaning up memory left over by the terminated child processes (see Section 3.5). 10.3.2 Executing the Default Action for the Signal If ka->sa.sa_handler is equal to SIG_DFL, do_signal( ) must perform the default action of the signal. The only exception comes when the receiving process is init, in which case the signal is discarded as described in the earlier section Section 10.1.1: if (current->pid == 1) continue; For other processes, since the default action depends on the type of signal, the function executes a switch statement based on the value of signr. The signals whose default action is "ignore" are easily handled: case SIGCONT: case SIGCHLD: case SIGWINCH: continue; The signals whose default action is "stop" may stop the current process. To do this, do_signal( ) sets the state of current to TASK_STOPPED and then invokes the schedule( ) function (see Section 11.2.2). The do_signal( ) function also sends a SIGCHLD signal to the parent process of current, unless the parent has set the SA_NOCLDSTOP flag of SIGCHLD: case SIGTSTP: case SIGTTIN: case SIGTTOU: if (is_orphaned_pgrp(current->pgrp)) continue; case SIGSTOP: current->state = TASK_STOPPED; current->exit_code = signr; if (current->p_pptr->sig && !(SA_NOCLDSTOP & current->p_pptr->sig->action[SIGCHLD-1].sa.sa_flags)) notify_parent(current, SIGCHLD); schedule( ); continue; The difference between SIGSTOP and the other signals is subtle: SIGSTOP always stops the process, while the other signals stop the process only if it is not in an "orphaned process group." The POSIX standard specifies that a process group is not orphaned as long as there is a process in the group that has a parent in a different process group but in the same session. The signals whose default action is "dump" may create a core file in the process working directory; this file lists the complete contents of the process's address space and CPU registers. After the do_signal( ) creates the core file, it kills the process. The default action of the remaining 18 signals is "terminate," which consists of just killing the process: exit_code = sig_nr; case SIGQUIT: case SIGILL: case SIGTRAP: case SIGABRT: case SIGFPE: case SIGSEGV: case SIGBUS: case SIGSYS: case SIGXCPU: case SIGXFSZ: if (do_coredump(signr, regs)) exit_code |= 0x80; default: sigaddset(¤t->pending.signal, signr); recalc_sigpending(current); current->flags |= PF_SIGNALED; do_exit(exit_code); The do_exit( ) function receives as its input parameter the signal number ORed with a flag set when a core dump has been performed. That value is used to set the exit code of the process. The function terminates the current process, and hence never returns (see Chapter 20). 10.3.3 Catching the Signal If a handler has been established for the signal, the do_signal( ) function must enforce its execution. It does this by invoking handle_signal( ): handle_signal(signr, ka, &info, oldset, regs); return 1; Notice how do_signal( ) returns after having handled a single signal. Other pending signals won't be considered until the next invocation of do_signal( ). This approach ensures that real-time signals will be dealt with in the proper order. Executing a signal handler is a rather complex task because of the need to juggle stacks carefully while switching between User Mode and Kernel Mode. We explain exactly what is entailed here. Signal handlers are functions defined by User Mode processes and included in the User Mode code segment. The handle_signal( ) function runs in Kernel Mode while signal handlers run in User Mode; this means that the current process must first execute the signal handler in User Mode before being allowed to resume its "normal" execution. Moreover, when the kernel attempts to resume the normal execution of the process, the Kernel Mode stack no longer contains the hardware context of the interrupted program because the Kernel Mode stack is emptied at every transition from User Mode to Kernel Mode. An additional complication is that signal handlers may invoke system calls. In this case, after the service routine executes, control must be returned to the signal handler instead of to the code of the interrupted program. The solution adopted in Linux consists of copying the hardware context saved in the Kernel Mode stack onto the User Mode stack of the current process. The User Mode stack is also modified in such a way that, when the signal handler terminates, the sigreturn( ) system call is automatically invoked to copy the hardware context back on the Kernel Mode stack and restore the original content of the User Mode stack. Figure 10-2 illustrates the flow of execution of the functions involved in catching a signal. A nonblocked signal is sent to a process. When an interrupt or exception occurs, the process switches into Kernel Mode. Right before returning to User Mode, the kernel executes the do_signal( ) function, which in turn handles the signal (by invoking handle_signal( )) and sets up the User Mode stack (by invoking setup_frame( ) or setup_rt_frame( )). When the process switches again to User Mode, it starts executing the signal handler because the handler's starting address was forced into the program counter. When that function terminates, the return code placed on the User Mode stack by the setup_frame( ) or setup_rt_frame( ) function is executed. This code invokes the sigreturn( ) system call, whose service routine copies the hardware context of the normal program in the Kernel Mode stack and restores the User Mode stack back to its original state (by invoking restore_sigcontext( )). When the system call terminates, the normal program can thus resume its execution. Figure 10-2. Catching a signal Let's now examine in detail how this scheme is carried out. 10.3.3.1 Setting up the frame To properly set the User Mode stack of the process, the handle_signal( ) function invokes either setup_frame( ) (for signals that do not require a siginfo_t table; see Section 10.4 later in this chapter) or setup_rt_frame( ) (for signals that do require a siginfo_t table). To choose among these two functions, the kernel checks the value of the SA_SIGINFO flag in the sa_flags field of the sigaction table associated with the signal. The setup_frame( ) function receives four parameters, which have the following meanings: sig Signal number ka Address of the k_sigaction table associated with the signal oldset Address of a bit mask array of blocked signals regs Address in the Kernel Mode stack area where the User Mode register contents are saved The setup_frame( ) function pushes onto the User Mode stack a data structure called a frame, which contains the information needed to handle the signal and to ensure the correct return to the sys_sigreturn( ) function. A frame is a sigframe table that includes the following fields (see Figure 10-3): pretcode Return address of the signal handler function; it points to the retcode field (later in this list) in the same table. sig The signal number; this is the parameter required by the signal handler. sc Structure of type sigcontext containing the hardware context of the User Mode process right before switching to Kernel Mode (this information is copied from the Kernel Mode stack of current). It also contains a bit array that specifies the blocked regular signals of the process. fpstate Structure of type _fpstate that may be used to store the floating point registers of the User Mode process (see Section 3.3.4). extramask Bit array that specifies the blocked real-time signals. retcode Eight-byte code issuing a sigreturn( ) system call; this code is executed when returning from the signal handler. Figure 10-3. Frame on the User Mode stack The setup_frame( ) function starts by invoking get_sigframe( ) to compute the first memory location of the frame. That memory location is usually[4] in the User Mode stack, so the function returns the value: [4] Linux allows processes to specify an alternate stack for their signal handlers by invoking the sigaltstack( ) system call; this feature is also requested by the X/Open standard. When an alternate stack is present, the get_sigframe( ) function returns an address inside that stack. We don't discuss this feature further, since it is conceptually similar to regular signal handling. (regs->esp - sizeof(struct sigframe)) & 0xfffffff8 Since stacks grow toward lower addresses, the initial address of the frame is obtained by subtracting its size from the address of the current stack top and aligning the result to a multiple of 8. The returned address is then verified by means of the access_ok macro; if it is valid, the function repeatedly invokes _ _put_user( ) to fill all the fields of the frame. Once this is done, it modifies the regs area of the Kernel Mode stack, thus ensuring that control is transferred to the signal handler when current resumes its execution in User Mode: regs->esp = (unsigned long) frame; regs->eip = (unsigned long) ka->sa.sa_handler; The setup_frame( ) function terminates by resetting the segmentation registers saved on the Kernel Mode stack to their default value. Now the information needed by the signal handler is on the top of the User Mode stack. The setup_rt_frame( ) function is very similar to setup_frame( ), but it puts on the User Mode stack an extended frame (stored in the rt_sigframe data structure) that also includes the content of the siginfo_t table associated with the signal. 10.3.3.2 Evaluating the signal flags After setting up the User Mode stack, the handle_signal( ) function checks the values of the flags associated with the signal. If the received signal has the SA_ONESHOT flag set, it must be reset to its default action so that further occurrences of the same signal will not trigger the execution of the signal handler: if (ka->sa.sa_flags & SA_ONESHOT) ka->sa.sa_handler = SIG_DFL; Moreover, if the signal does not have the SA_NODEFER flag set, the signals in the sa_mask field of the sigaction table must be blocked during the execution of the signal handler: if (!(ka->sa.sa_flags & SA_NODEFER)) { spin_lock_irq(¤t->sigmask_lock); sigorsets(¤t->blocked, ¤t->blocked, &ka->sa.sa_mask); sigaddset(¤t->blocked, sig); recalc_sigpending(current); spin_unlock_irq(¤t->sigmask_lock); } As described earlier, the recalc_sigpending( ) function checks whether the process has nonblocked pending signals and sets its sigpending field accordingly. The function returns then to do_signal( ), which also returns immediately. 10.3.3.3 Starting the signal handler When do_signal( ) returns, the current process resumes its execution in User Mode. Because of the preparation by setup_frame( ) described earlier, the eip register points to the first instruction of the signal handler, while esp points to the first memory location of the frame that has been pushed on top of the User Mode stack. As a result, the signal handler is executed. 10.3.3.4 Terminating the signal handler When the signal handler terminates, the return address on top of the stack points to the code in the retcode field of the frame. For signals without siginfo_t table, the code is equivalent to the following assembly language instructions: popl %eax movl $_ _NR_sigreturn, %eax int $0x80 Therefore, the signal number (that is, the sig field of the frame) is discarded from the stack, and the sigreturn( ) system call is then invoked. The sys_sigreturn( ) function computes the address of the pt_regs data structure regs, which contains the hardware context of the User Mode process (see Section 9.2.3). From the value stored in the esp field, it can thus derive and check the frame address inside the User Mode stack: frame = (struct sigframe *)(regs.esp - 8); if (verify_area(VERIFY_READ, frame, sizeof(*frame)) { force_sig(SIGSEGV, current); return 0; } Then the function copies the bit array of signals that were blocked before invoking the signal handler from the sc field of the frame to the blocked field of current. As a result, all signals that have been masked for the execution of the signal handler are unblocked. The recalc_sigpending( ) function is then invoked. The sys_sigreturn( ) function must at this point copy the process hardware context from the sc field of the frame to the Kernel Mode stack and remove the frame from the User Mode stack; it performs these two tasks by invoking the restore_sigcontext( ) function. If the signal was sent by a system call like rt_sigqueueinfo( ) that required a siginfo_t table to be associated to the signal, the mechanism is very similar. The return code in the retcode field of the extended frame invokes the rt_sigreturn( ) system call; the corresponding sys_rt_sigreturn( ) service routine copies the process hardware context from the extended frame to the Kernel Mode stack and restores the original User Mode stack content by removing the extended frame from it. 10.3.4 Reexecution of System Calls The request associated with a system call cannot always be immediately satisfied by the kernel; when this happens, the process that issued the system call is put in a TASK_INTERRUPTIBLE or TASK_UNINTERRUPTIBLE state. If the process is put in a TASK_INTERRUPTIBLE state and some other process sends a signal to it, the kernel puts it in the TASK_RUNNING state without completing the system call (see Section 4.8). When this happens, the system call service routine does not complete its job, but returns an EINTR, ERESTARTNOHAND, ERESTARTSYS, or ERESTARTNOINTR error code. The signal is delivered to the process while switching back to User Mode. In practice, the only error code a User Mode process can get in this situation is EINTR, which means that the system call has not been completed. (The application programmer may check this code and decide whether to reissue the system call.) The remaining error codes are used internally by the kernel to specify whether the system call may be reexecuted automatically after the signal handler termination. Table 10-6 lists the error codes related to unfinished system calls and their impact for each of the three possible signal actions. The terms that appear in the entries are defined in the following list: Terminate The system call will not be automatically reexecuted; the process will resume its execution in User Mode at the instruction following the int $0x80 one and the eax register will contain the -EINTR value. Reexecute The kernel forces the User Mode process to reload the eax register with the system call number and to reexecute the int $0x80 instruction; the process is not aware of the reexecution and the error code is not passed to it. Depends The system call is reexecuted only if the SA_RESTART flag of the delivered signal is set; otherwise, the system call terminates with a -EINTR error code. Table 10-6. Reexecution of system calls Signal Action Error codes and their impact on system call execution EINTR ERESTARTSYS ERESTARTNOHAND ERESTARTNOINTR Default Terminate Reexecute Reexecute Reexecute Ignore Terminate Reexecute Reexecute Reexecute Catch Terminate Depends Terminate Reexecute When delivering a signal, the kernel must be sure that the process really issued a system call before attempting to reexecute it. This is where the orig_eax field of the regs hardware context plays a critical role. Let's recall how this field is initialized when the interrupt or exception handler starts: Interrupt The field contains the IRQ number associated with the interrupt minus 256 (see Section 4.6.1.4). 0x80 exception The field contains the system call number (see Section 9.2.2). Other exceptions The field contains the value -1 (see Section 4.5.1). Therefore, a non-negative value in the orig_eax field means that the signal has woken up a TASK_INTERRUPTIBLE process that was sleeping in a system call. The service routine recognizes that the system call was interrupted, and thus returns one of the previously mentioned error codes. If the signal is explicitly ignored or if its default action is enforced, do_signal( ) analyzes the error code of the system call to decide whether the unfinished system call must be automatically reexecuted, as specified in Table 10-6. If the call must be restarted, the function modifies the regs hardware context so that, when the process is back in User Mode, eip points to the int $0x80 instruction and eax contains the system call number: if (regs->orig_eax >= 0) { if (regs->eax == -ERESTARTNOHAND || regs->eax == -ERESTARTSYS || regs->eax == -ERESTARTNOINTR) { regs->eax = regs->orig_eax; regs->eip -= 2; } } The regs->eax field is filled with the return code of a system call service routine (see Section 9.2.2). If the signal is caught, handle_signal( ) analyzes the error code and, possibly, the SA_RESTART flag of the sigaction table to decide whether the unfinished system call must be reexecuted: if (regs->orig_eax >= 0) { switch (regs->eax) { case -ERESTARTNOHAND: regs->eax = -EINTR; break; case -ERESTARTSYS: if (!(ka->sa.sa_flags & SA_RESTART)) { regs->eax = -EINTR; break; } /* fallthrough */ case -ERESTARTNOINTR: regs->eax = regs->orig_eax; regs->eip -= 2; } } If the system call must be restarted, handle_signal( ) proceeds exactly as do_signal( ); otherwise, it returns an -EINTR error code to the User Mode process. I l@ve RuBoard I l@ve RuBoard 10.4 System Calls Related to Signal Handling As stated in the introduction of this chapter, programs running in User Mode are allowed to send and receive signals. This means that a set of system calls must be defined to allow these kinds of operations. Unfortunately, for historical reasons, several system calls exist that serve essentially the same purpose. As a result, some of these system calls are never invoked. For instance, sys_sigaction( ) and sys_rt_sigaction( ) are almost identical, so the sigaction( ) wrapper function included in the C library ends up invoking sys_rt_sigaction( ) instead of sys_sigaction( ). We shall describe some of the most significant POSIX system calls. 10.4.1 The kill( ) System Call The kill(pid,sig) system call is commonly used to send signals; its corresponding service routine is the sys_kill( ) function. The integer pid parameter has several meanings, depending on its numerical value: pid > 0 The sig signal is sent to the process whose PID is equal to pid. pid = 0 The sig signal is sent to all processes in the same group as the calling process. pid = -1 The signal is sent to all processes, except swapper (PID 0), init (PID 1), and current. pid < -1 The signal is sent to all processes in the process group -pid. The sys_kill( ) function sets up a minimal siginfo_t table for the signal, and then invokes kill_something_info( ): info.si_signo = sig; info.si_errno = 0; info.si_code = SI_USER; info._sifields._kill._pid = current->pid; info._sifields._kill._uid = current->uid; return kill_something_info(sig, &info, pid); The kill_something_info( ) function, in turn, invokes either send_sig_info( ) (to send the signal to a single process), or kill_pg_info( ) (to scan all processes and invoke send_sig_info( ) for each process in the destination group). The kill( ) system call is able to send any signal, even the so-called real-time signals that have numbers ranging from 32 to 63. However, as we saw in the earlier section Section 10.2, the kill( ) system call does not ensure that a new element is added to the pending signal queue of the destination process, thus multiple instances of pending signals can be lost. Real-time signals should be sent by means of a system call like rt_sigqueueinfo( ) (see the later section Section 10.4.6). System V and BSD Unix variants also have a killpg( ) system call, which is able to explicitly send a signal to a group of processes. In Linux, the function is implemented as a library function that uses the kill( ) system call. Another variation is raise( ), which sends a signal to the current process (that is, to the process executing the function). In Linux, raise() is implemented as a library function. 10.4.2 Changing a Signal Action The sigaction(sig,act,oact) system call allows users to specify an action for a signal; of course, if no signal action is defined, the kernel executes the default action associated with the delivered signal. The corresponding sys_sigaction( ) service routine acts on two parameters: the sig signal number and the act table of type sigaction that specifies the new action. A third oact optional output parameter may be used to get the previous action associated with the signal. The function checks first whether the act address is valid. Then it fills the sa_handler, sa_flags, and sa_mask fields of a new_ka local variable of type k_sigaction with the corresponding fields of *act: _ _get_user(new_ka.sa.sa_handler, &act->sa_handler); _ _get_user(new_ka.sa.sa_flags, &act->sa_flags); _ _get_user(mask, &act->sa_mask); siginitset(&new_ka.sa.sa_mask, mask); The function invokes do_sigaction( ) to copy the new new_ka table into the entry at the sig-1 position of current->sig->action (the number of the signal is one higher than the position in the array because there is no zero signal): k = ¤t->sig->action[sig-1]; spin_lock(¤t->sig->siglock); if (act) { *k = *act; sigdelsetmask(&k->sa.sa_mask, sigmask(SIGKILL) | sigmask(SIGSTOP)); if (k->sa.sa_handler == SIG_IGN || (k->sa.sa_handler == SIG_DFL && (sig == SIGCONT || sig == SIGCHLD || sig == SIGWINCH))) { spin_lock_irq(¤t->sigmask_lock); if (rm_sig_from_queue(sig, current)) recalc_sigpending(current); spin_unlock_irq(¤t->sigmask_lock); } } The POSIX standard requires that setting a signal action to either SIG_IGN or SIG_DFL when the default action is "ignore," causes any pending signal of the same type to be discarded. Moreover, notice that no matter what the requested masked signals are for the signal handler, SIGKILL and SIGSTOP are never masked. If the oact parameter is not NULL, the contents of the previous sigaction table are copied to the process address space at the address specified by that parameter: if (oact) { _ _put_user(old_ka.sa.sa_handler, &oact->sa_handler); _ _put_user(old_ka.sa.sa_flags, &oact->sa_flags); _ _put_user(old_ka.sa.sa_mask.sig[0], &oact->sa_mask); } Notice that the sigaction( ) system call also allows initialization of the sa_flags field in the sigaction table. We listed the values allowed for this field and the related meanings in Table 10-4 (earlier in this chapter). Older System V Unix variants offered the signal( ) system call, which is still widely used by programmers. Recent C libraries implement signal( ) by means of sigaction( ). However, Linux still supports older C libraries and offers the sys_signal( ) service routine: new_sa.sa.sa_handler = handler; new_sa.sa.sa_flags = SA_ONESHOT | SA_NOMASK; ret = do_sigaction(sig, &new_sa, &old_sa); return ret ? ret : (unsigned long)old_sa.sa.sa_handler; 10.4.3 Examining the Pending Blocked Signals The sigpending( ) system call allows a process to examine the set of pending blocked signals—i.e., those that have been raised while blocked. The corresponding sys_sigpending( ) service routine acts on a single parameter, set, namely, the address of a user variable where the array of bits must be copied: spin_lock_irq(¤t->sigmask_lock); sigandsets(&pending, ¤t->blocked, ¤t->pending.signal); spin_unlock_irq(¤t->sigmask_lock); copy_to_user(set, &pending, sizeof(sigset_t)); 10.4.4 Modifying the Set of Blocked Signals The sigprocmask( ) system call allows processes to modify the set of blocked signals; it applies only to regular (non-real-time) signals. The corresponding sys_sigprocmask( ) service routine acts on three parameters: oset Pointer in the process address space to a bit array where the previous bit mask must be stored set Pointer in the process address space to the bit array containing the new bit mask how Flag that may have one of the following values: SIG_BLOCK The *set bit mask array specifies the signals that must be added to the bit mask array of blocked signals. SIG_UNBLOCK The *set bit mask array specifies the signals that must be removed from the bit mask array of blocked signals. SIG_SETMASK The *set bit mask array specifies the new bit mask array of blocked signals. The function invokes copy_from_user( ) to copy the value pointed to by the set parameter into the new_set local variable and copies the bit mask array of standard blocked signals of current into the old_set local variable. It then acts as the how flag specifies on these two variables: if (copy_from_user(&new_set, set, sizeof(*set))) return -EFAULT; new_set &= ~(sigmask(SIGKILL)|sigmask(SIGSTOP)); spin_lock_irq(¤t->sigmask_lock); old_set = current->blocked.sig[0]; if (how == SIG_BLOCK) sigaddsetmask(¤t->blocked, new_set); else if (how == SIG_UNBLOCK) sigdelsetmask(¤t->blocked, new_set); else if (how == SIG_SETMASK) current->blocked.sig[0] = new_set; else return -EINVAL; recalc_sigpending(current); spin_unlock_irq(¤t->sigmask_lock); if (oset) { if (copy_to_user(oset, &old_set, sizeof(*oset))) return -EFAULT; } return 0; 10.4.5 Suspending the Process The sigsuspend( ) system call puts the process in the TASK_INTERRUPTIBLE state, after having blocked the standard signals specified by a bit mask array to which the mask parameter points. The process will wake up only when a nonignored, nonblocked signal is sent to it. The corresponding sys_sigsuspend( ) service routine executes these statements: mask &= ~(sigmask(SIGKILL) | sigmask(SIGSTOP)); spin_lock_irq(¤t->sigmask_lock); saveset = current->blocked; siginitset(¤t->blocked, mask); recalc_sigpending(current); spin_unlock_irq(¤t->sigmask_lock); regs->eax = -EINTR; while (1) { current->state = TASK_INTERRUPTIBLE; schedule( ); if (do_signal(regs, &saveset)) return -EINTR; } The schedule( ) function selects another process to run. When the process that issued the sigsuspend( ) system call is executed again, sys_sigsuspend( ) invokes the do_signal( ) function to deliver the signal that has woken up the process. If that function returns the value 1, the signal is not ignored. Therefore the system call terminates by returning the error code -EINTR. The sigsuspend( ) system call may appear redundant, since the combined execution of sigprocmask( ) and sleep( ) apparently yields the same result. But this is not true: because of interleaving of process executions, one must be conscious that invoking a system call to perform action A followed by another system call to perform action B is not equivalent to invoking a single system call that performs action A and then action B. In the particular case, sigprocmask( ) might unblock a signal that is delivered before invoking sleep( ). If this happens, the process might remain in a TASK_INTERRUPTIBLE state forever, waiting for the signal that was already delivered. On the other hand, the sigsuspend( ) system call does not allow signals to be sent after unblocking and before the schedule( ) invocation because other processes cannot grab the CPU during that time interval. 10.4.6 System Calls for Real-Time Signals Since the system calls previously examined apply only to standard signals, additional system calls must be introduced to allow User Mode processes to handle real-time signals. Several system calls for real-time signals (rt_sigaction( ), rt_sigpending( ), rt_sigprocmask( ), and rt_sigsuspend( )) are similar to those described earlier and won't be discussed further. For the same reason, we won't discuss two other system calls that deal with queues of real-time signals: rt_sigqueueinfo( ) Sends a real-time signal so that it is added to the pending signal queue of the destination process rt_sigtimedwait( ) Dequeues a blocked pending signal without delivering it and returns the signal number to the caller; if no blocked signal is pending, suspends the current process for a fixed amount of time. I l@ve RuBoard I l@ve RuBoard Chapter 11. Process Scheduling Like any time-sharing system, Linux achieves the magical effect of an apparent simultaneous execution of multiple processes by switching from one process to another in a very short time frame. Process switching itself was discussed in Chapter 3; this chapter deals with scheduling, which is concerned with when to switch and which process to choose. The chapter consists of three parts. Section 11.1 introduces the choices made by Linux to schedule processes in the abstract. Section 11.2 discusses the data structures used to implement scheduling and the corresponding algorithm. Finally, Section 11.3 describes the system calls that affect process scheduling. I l@ve RuBoard I l@ve RuBoard 11.1 Scheduling Policy The scheduling algorithm of traditional Unix operating systems must fulfill several conflicting objectives: fast process response time, good throughput for background jobs, avoidance of process starvation, reconciliation of the needs of low- and high-priority processes, and so on. The set of rules used to determine when and how to select a new process to run is called scheduling policy. Linux scheduling is based on the time-sharing technique already introduced in Section 6.3: several processes run in "time multiplexing" because the CPU time is divided into "slices," one for each runnable process.[1] Of course, a single processor can run only one process at any given instant. If a currently running process is not terminated when its time slice or quantum expires, a process switch may take place. Time-sharing relies on timer interrupts and is thus transparent to processes. No additional code needs to be inserted in the programs to ensure CPU time-sharing. [1] Recall that stopped and suspended processes cannot be selected by the scheduling algorithm to run on the CPU. The scheduling policy is also based on ranking processes according to their priority. Complicated algorithms are sometimes used to derive the current priority of a process, but the end result is the same: each process is associated with a value that denotes how appropriate it is to be assigned to the CPU. In Linux, process priority is dynamic. The scheduler keeps track of what processes are doing and adjusts their priorities periodically; in this way, processes that have been denied the use of the CPU for a long time interval are boosted by dynamically increasing their priority. Correspondingly, processes running for a long time are penalized by decreasing their priority. When speaking about scheduling, processes are traditionally classified as "I/O-bound" or "CPU-bound." The former make heavy use of I/O devices and spend much time waiting for I/O operations to complete; the latter are number-crunching applications that require a lot of CPU time. An alternative classification distinguishes three classes of processes: Interactive processes These interact constantly with their users, and therefore spend a lot of time waiting for keypresses and mouse operations. When input is received, the process must be woken up quickly, or the user will find the system to be unresponsive. Typically, the average delay must fall between 50 and 150 milliseconds. The variance of such delay must also be bounded, or the user will find the system to be erratic. Typical interactive programs are command shells, text editors, and graphical applications. Batch processes These do not need user interaction, and hence they often run in the background. Since such processes do not need to be very responsive, they are often penalized by the scheduler. Typical batch programs are programming language compilers, database search engines, and scientific computations. Real-time processes These have very stringent scheduling requirements. Such processes should never be blocked by lower-priority processes and should have a short guaranteed response time with a minimum variance. Typical real-time programs are video and sound applications, robot controllers, and programs that collect data from physical sensors. The two classifications we just offered are somewhat independent. For instance, a batch process can be either I/O-bound (e.g., a database server) or CPU-bound (e.g., an image- rendering program). While real-time programs are explicitly recognized as such by the scheduling algorithm in Linux, there is no way to distinguish between interactive and batch programs. To offer a good response time to interactive applications, Linux (like all Unix kernels) implicitly favors I/O-bound processes over CPU-bound ones. Programmers may change the scheduling priorities by means of the system calls illustrated in Table 11-1. More details are given in Section 11.3. Table 11-1. System calls related to scheduling System call Description nice( ) Change the priority of a conventional process. getpriority( ) Get the maximum priority of a group of conventional processes. setpriority( ) Set the priority of a group of conventional processes. sched_getscheduler( ) Get the scheduling policy of a process. sched_setscheduler( ) Set the scheduling policy and priority of a process. sched_getparam( ) Get the priority of a process. sched_setparam( ) Set the priority of a process. sched_yield( ) Relinquish the processor voluntarily without blocking. sched_get_ priority_min( ) Get the minimum priority value for a policy. sched_get_ priority_max( ) Get the maximum priority value for a policy. sched_rr_get_interval( ) Get the time quantum value for the Round Robin policy. Most system calls shown in the table apply to real-time processes, thus allowing users to develop real-time applications. However, Linux does not support the most demanding real- time applications because its kernel is nonpreemptive (see the later section Section 11.2.3). 11.1.1 Process Preemption As mentioned in the first chapter, Linux processes are preemptive. If a process enters the TASK_RUNNING state, the kernel checks whether its dynamic priority is greater than the priority of the currently running process. If it is, the execution of current is interrupted and the scheduler is invoked to select another process to run (usually the process that just became runnable). Of course, a process may also be preempted when its time quantum expires. As mentioned in Section 6.3, when this occurs, the need_resched field of the current process is set, so the scheduler is invoked when the timer interrupt handler terminates. For instance, let's consider a scenario in which only two programs—a text editor and a compiler—are being executed. The text editor is an interactive program, so it has a higher dynamic priority than the compiler. Nevertheless, it is often suspended, since the user alternates between pauses for think time and data entry; moreover, the average delay between two keypresses is relatively long. However, as soon as the user presses a key, an interrupt is raised and the kernel wakes up the text editor process. The kernel also determines that the dynamic priority of the editor is higher than the priority of current, the currently running process (the compiler), so it sets the need_resched field of this process, thus forcing the scheduler to be activated when the kernel finishes handling the interrupt. The scheduler selects the editor and performs a process switch; as a result, the execution of the editor is resumed very quickly and the character typed by the user is echoed to the screen. When the character has been processed, the text editor process suspends itself waiting for another keypress and the compiler process can resume its execution. Be aware that a preempted process is not suspended, since it remains in the TASK_RUNNING state; it simply no longer uses the CPU. Some real-time operating systems feature preemptive kernels, which means that a process running in Kernel Mode can be interrupted after any instruction, just as it can in User Mode. The Linux kernel is not preemptive, which means that a process can be preempted only while running in User Mode; nonpreemptive kernel design is much simpler, since most synchronization problems involving the kernel data structures are easily avoided (see Section 5.2). 11.1.2 How Long Must a Quantum Last? The quantum duration is critical for system performances: it should be neither too long nor too short. If the quantum duration is too short, the system overhead caused by process switches becomes excessively high. For instance, suppose that a process switch requires 10 milliseconds; if the quantum is also set to 10 milliseconds, then at least 50 percent of the CPU cycles will be dedicated to process switching.[2] [2] Actually, things could be much worse than this; for example, if the time required for the process switch is counted in the process quantum, all CPU time is devoted to the process switch and no process can progress toward its termination. If the quantum duration is too long, processes no longer appear to be executed concurrently. For instance, let's suppose that the quantum is set to five seconds; each runnable process makes progress for about five seconds, but then it stops for a very long time (typically, five seconds times the number of runnable processes). It is often believed that a long quantum duration degrades the response time of interactive applications. This is usually false. As described in Section 11.1.1 earlier in this chapter, interactive processes have a relatively high priority, so they quickly preempt the batch processes, no matter how long the quantum duration is. In some cases, a quantum duration that is too long degrades the responsiveness of the system. For instance, suppose two users concurrently enter two commands at the respective shell prompts; one command is CPU-bound, while the other is an interactive application. Both shells fork a new process and delegate the execution of the user's command to it; moreover, suppose such new processes have the same priority initially (Linux does not know in advance if an executed program is batch or interactive). Now if the scheduler selects the CPU-bound process to run, the other process could wait for a whole time quantum before starting its execution. Therefore, if such duration is long, the system could appear to be unresponsive to the user that launched it. The choice of quantum duration is always a compromise. The rule of thumb adopted by Linux is choose a duration as long as possible, while keeping good system response time. I l@ve RuBoard I l@ve RuBoard 11.2 The Scheduling Algorithm The Linux scheduling algorithm works by dividing the CPU time into epochs. In a single epoch, every process has a specified time quantum whose duration is computed when the epoch begins. In general, different processes have different time quantum durations. The time quantum value is the maximum CPU time portion assigned to the process in that epoch. When a process has exhausted its time quantum, it is preempted and replaced by another runnable process. Of course, a process can be selected several times from the scheduler in the same epoch, as long as its quantum has not been exhausted—for instance, if it suspends itself to wait for I/O, it preserves some of its time quantum and can be selected again during the same epoch. The epoch ends when all runnable processes have exhausted their quanta; in this case, the scheduler algorithm recomputes the time-quantum durations of all processes and a new epoch begins. Each process has a base time quantum, which is the time-quantum value assigned by the scheduler to the process if it has exhausted its quantum in the previous epoch. The users can change the base time quantum of their processes by using the nice( ) and setpriority( ) system calls (see Section 11.3 later in this chapter). A new process always inherits the base time quantum of its parent. The INIT_TASK macro sets the value of the initial time quantum of process 0 (swapper) to DEF_COUNTER; that macro is defined as follows: #define DEF_COUNTER ( 10 * HZ / 100) Since HZ (which denotes the frequency of timer interrupts) is set to 100 for IBM compatible PCs (see Section 6.1.3), the value of DEF_COUNTER is 10 ticks—that is, about 105 ms. To select a process to run, the Linux scheduler must consider the priority of each process. Actually, there are two kinds of priorities: Static priority This is assigned by the users to real-time processes and ranges from 1 to 99. It is never changed by the scheduler. Dynamic priority This applies only to conventional processes; it is essentially the sum of the base time quantum (which is therefore also called the base priority of the process) and of the number of ticks of CPU time left to the process before its quantum expires in the current epoch. Of course, the static priority of a real-time process is always higher than the dynamic priority of a conventional one. The scheduler starts running conventional processes only when there is no real-time process in a TASK_RUNNING state. There is always at least one runnable process: the swapper kernel thread, which has PID 0 and executes only when the CPU cannot execute other processes. As mentioned in Chapter 3, every CPU of a multiprocessor system has its own kernel thread with PID equal to 0. 11.2.1 Data Structures Used by the Scheduler Recall from Section 3.2 that the process list links all process descriptors, while the runqueue list links the process descriptors of all runnable processes—that is, of those in a TASK_RUNNING state. In both cases, the init_task process descriptor plays the role of list header. 11.2.1.1 Process descriptor Each process descriptor includes several fields related to scheduling: need_resched A flag checked by ret_from_sys_call( ) to decide whether to invoke the schedule( ) function (see Section 4.8.3).[3] [3] Beside the values 0 (false) and 1 (true), the need_resched field of a swapper kernel thread (PID 0) in a multiprocessor system can also assume the value - 1; see the later section Section 11.2.2.6 for details. policy The scheduling class. The values permitted are: SCHED_FIFO A First-In, First-Out real-time process. When the scheduler assigns the CPU to the process, it leaves the process descriptor in its current position in the runqueue list. If no other higher-priority real-time process is runnable, the process continues to use the CPU as long as it wishes, even if other real-time processes that have the same priority are runnable. SCHED_RR A Round Robin real-time process. When the scheduler assigns the CPU to the process, it puts the process descriptor at the end of the runqueue list. This policy ensures a fair assignment of CPU time to all SCHED_RR real-time processes that have the same priority. SCHED_OTHER A conventional, time-shared process. The policy field also encodes a SCHED_YIELD binary flag. This flag is set when the process invokes the sched_ yield( ) system call (a way of voluntarily relinquishing the processor without the need to start an I/O operation or go to sleep; see the later section Section 11.3). The kernel also sets the SCHED_YIELD flag and invokes the schedule( ) function whenever it is executing a long noncritical task and wishes to give other processes a chance to run. rt_priority The static priority of a real-time process; valid priorities range between 1 and 99. The static priority of a conventional process must be set to 0. counter The number of ticks of CPU time left to the process before its quantum expires; when a new epoch begins, this field contains the time-quantum duration of the process. Recall that the update_process_times( ) function decrements the counter field of the current process by 1 at every tick. nice Determines the length of the process time quantum when a new epoch begins. This field contains values ranging between - 20 and + 19; negative values correspond to "high priority" processes, positive ones to "low priority" processes. The default value 0 corresponds to normal processes. cpus_allowed A bit mask specifying the CPUs on which the process is allowed to run. In the 80 x 86 architecture, the maximum number of processor is set to 32, so the whole mask can be encoded in a single integer field. cpus_runnable A bit mask specifying the CPU that is executing the process, if any. If the process is not executed by any CPU, all bits of the field are set to 1. Otherwise, all bits of the field are set to 0, except the bit associated with the executing CPU, which is set to 1. This encoding allows the kernel to verify whether the process can be scheduled on a given CPU by simply computing the logical AND between this field, the cpus_allowed field, and the bit mask specifying the CPU. processor The index of the CPU that is executing the process, if any; otherwise, the index of the last CPU that executed the process. When a new process is created, do_fork( ) sets the counter field of both current (the parent) and p (the child) processes in the following way: p->counter = (current->counter + 1) >> 1; current->counter >>= 1; if (!current->counter) current->need_resched = 1; In other words, the number of ticks left to the parent is split in two halves: one for the parent and one for the child. This is done to prevent users from getting an unlimited amount of CPU time by using the following method: the parent process creates a child process that runs the same code and then kills itself; by properly adjusting the creation rate, the child process would always get a fresh quantum before the quantum of its parent expires. This programming trick does not work since the kernel does not reward forks. Similarly, a user cannot hog an unfair share of the processor by starting lots of background processes in a shell or by opening a lot of windows on a graphical desktop. More generally speaking, a process cannot hog resources (unless it has privileges to give itself a real-time policy) by forking multiple descendents. 11.2.1.2 CPU's data structures Besides the fields included in each process descriptor, additional information is needed to describe what each CPU is doing. To that end, the scheduler can rely on the aligned_data array of NR_CPUS structures of type schedule_data. Each such structure consists of two fields: curr A pointer to the process descriptor of the process running on that CPU. The field is usually accessed by means of the cpu_curr(n) macro, where n is the CPU logical number. last_schedule The value of the 64-bit Time Stamp Counter when the last process switch was performed on the CPU. The field is usually accessed by means of the last_schedule(n) macro, where n is the CPU logical number. Most of the time, any CPU accesses only its own array element; it is thus convenient to align the entries of the aligned_data array so that every element falls in a different cache line. In this way, the CPUs have a better chance to find their own element in the hardware cache. 11.2.2 The schedule( ) Function The schedule( ) function implements the scheduler. Its objective is to find a process in the runqueue list and then assign the CPU to it. It is invoked, directly or in a lazy (deferred) way, by several kernel routines. 11.2.2.1 Direct invocation The scheduler is invoked directly when the current process must be blocked right away because the resource it needs is not available. In this case, the kernel routine that wants to block it proceeds as follows: 1. Inserts current in the proper wait queue 2. Changes the state of current either to TASK_INTERRUPTIBLE or to TASK_UNINTERRUPTIBLE 3. Invokes schedule( ) 4. Checks whether the resource is available; if not, goes to Step 2 5. Once the resource is available, removes current from the wait queue As can be seen, the kernel routine checks repeatedly whether the resource needed by the process is available; if not, it yields the CPU to some other process by invoking schedule( ). Later, when the scheduler once again grants the CPU to the process, the availability of the resource is rechecked. These steps are similar to those performed by the sleep_on( ) and interruptible_sleep_on( ) functions described in Section 3.2.4. The scheduler is also directly invoked by many device drivers that execute long iterative tasks. At each iteration cycle, the driver checks the value of the need_resched field and, if necessary, invokes schedule( ) to voluntarily relinquish the CPU. 11.2.2.2 Lazy invocation The scheduler can also be invoked in a lazy way by setting the need_resched field of current to 1. Since a check on the value of this field is always made before resuming the execution of a User Mode process (see Section 4.8), schedule( ) will definitely be invoked at some time in the near future. For instance, lazy invocation of the scheduler is performed in the following cases: ● When current has used up its quantum of CPU time; this is done by the update_process_times( ) function. ● When a process is woken up and its priority is higher than that of the current process; this task is performed by the reschedule_idle( ) function, which is usually invoked by the wake_up_process( ) function (see Section 3.2.2). ● When a sched_setscheduler( ) or sched_ yield( ) system call is issued (see Section 11.3 later in this chapter). 11.2.2.3 Actions performed by schedule( ) before a process switch The goal of the schedule( ) function consists of replacing the currently executing process with another one. Thus, the key outcome of the function is to set a local variable called next so that it points to the descriptor of the process selected to replace current. If no runnable process in the system has priority greater than the priority of current, at the end, next coincides with current and no process switch takes place. For efficiency reasons, the schedule( ) function starts by initializing a few local variables: prev = current; this_cpu = prev->processor; sched_data = & aligned_data[this_cpu]; As you see, the pointer returned by current is saved in prev, the logical number of the executing CPU is saved in this_cpu, and the pointer to the aligned_data array element of the CPU is saved in sched_data. Next, schedule( ) makes sure that prev doesn't hold the global kernel lock or the global interrupt lock (see Section 5.5.2 and Section 5.3.10), and then reenables the local interrupts: if (prev->lock_depth >= 0) spin_unlock(&kernel_flag); release_irqlock(this_cpu); _ _sti( ); Generally speaking, a process should never hold a lock across a process switch; otherwise, the system freezes as soon as another process tries to acquire the same lock.However, notice that schedule( ) doesn't change the value of the lock_depth field; when prev resumes its execution, it reacquires the kernel_flag spin lock if the value of this field is not negative. Thus, the global kernel lock is automatically released and reacquired across a process switch. Conversely, the global interrupt lock is not automatically reacquired. Before starting to look at the runnable processes, schedule( ) must disable the local interrupts and acquire the spin lock that protects the runqueue (see section Section 3.2.2.5): spin_lock_irq(&runqueue_lock); A check is then made to determine whether prev is a Round Robin real-time process (policy field set to SCHED_RR) that has exhausted its quantum. If so, schedule( ) assigns a new quantum to prev and puts it at the bottom of the runqueue list: if (prev->policy == SCHED_RR && !prev->counter) { prev->counter = (20 - prev->nice) / 4 + 1; move_last_runqueue(prev); } Recall that the nice field of a process ranges between - 20 and + 19; therefore, schedule( ) replenishes the counter field with a number of ticks ranging from 11 to 1. The default value of the nice field is 0, so usually the process gets a new quantum of 6 ticks, roughly 60 ms.[4] [4] Recall that in the 80 x 86 architecture, 1 tick corresponds to roughly 10 ms (see Section 6.1.3). In all architectures, however, the formula that computes the number of ticks in a quantum is adapted so the default quantum has an order of magnitude of 50 ms. Next, schedule( ) examines the state of prev. If it has nonblocked pending signals and its state is TASK_INTERRUPTIBLE, the function sets the process state to TASK_RUNNING. This action is not the same as assigning the processor to prev; it just gives prev a chance to be selected for execution: if (prev->state == TASK_INTERRUPTIBLE && signal_pending(prev)) prev->state = TASK_RUNNING; If prev is not in the TASK_RUNNING state, schedule( ) was directly invoked by the process itself because it had to wait on some external resource; therefore, prev must be removed from the runqueue list: if (prev->state != TASK_RUNNING) del_from_runqueue(prev); The function also resets the need_resched field of current, just in case the scheduler was activated in the lazy way: prev->need_resched = 0; Now the time has come for schedule( ) to select the process to be executed in the next time quantum. To that end, the function scans the runqueue list. The objective is to store in next the process descriptor pointer of the highest priority process: repeat_schedule: next = init_tasks[this_cpu]; c = -1000; list_for_each(tmp, &runqueue_head) { p = list_entry(tmp, struct task_struct, run_list); if (p->cpus_runnable & p->cpus_allowed & (1 << this_cpu)) { int weight = goodness(p, this_cpu, prev->active_mm); if (weight > c) c = weight, next = p; } } The function initializes next so it points to the process referenced by init_task[this_cpu]—that is, to the process (swapper) associated with the executing CPU; the c local variable is set to - 1000. As we shall see in the later section Section 11.2.2.5, the goodness( ) function returns an integer that denotes the priority of the process passed as parameter. While scanning processes in the runqueue, schedule( ) considers only those that are both: 1. Runnable on the executing CPU (cpus_allowed & (1<counter = (p->counter >> 1) + (20 - p->nice) / 4 + 1; read_unlock(&tasklist_lock); spin_lock_irq(&runqueue_lock); goto repeat_schedule; } In this way, suspended or stopped processes have their dynamic priorities periodically increased. As stated earlier, the rationale for increasing the counter value of suspended or stopped processes is to give preference to I/O-bound processes. However, no matter how often the quantum is increased, its value can never become greater than about 230 ms.[5] [5] For the mathematically inclined, here is a sketch of the proof: when a new epoch starts, the value of counter is bounded by half of the previous value of counter plus P , which is the maximum value that can be added to counter. If nice is set to -20, then P is equal to 11 ticks. Solving the recurrence equation yields as upper bound the geometric series P x ( 1 + 1/2 + 1/4 + 1/8 + . . . ), which converges to 2 x P (that is, 22 ticks). Let's assume now that schedule( ) has selected its best candidate, and that next points to its process descriptor. The function updates the aligned_data array element of the executing CPU (this element is referenced by the sched_data local variable), writes the index of the executing CPU in next's process descriptor, releases the runqueue list spin lock, and reenables local interrupts: sched_data->curr = next; next->processor = this_cpu; next->cpus_runnable = 1UL << this_cpu; spin_unlock_irq(&runqueue_lock); Now schedule( ) is ready to proceed with the actual process switch. But wait a moment! If the next best candidate is the previously running process prev, schedule( ) can terminate: if (prev == next) { prev->policy &= ~SCHED_YIELD; if (prev->lock_depth >= 0) spin_lock(&kernel_flag); return; } Notice that schedule( ) reacquires the global kernel lock if the lock_depth field of the process is not negative, as we anticipated when we described the first actions of the function. If a process other than prev is selected, a process switch must take place. The current value of the Time Stamp Counter, fetched by means of the rdtsc assembly language instruction, is stored in the last_schedule field of the aligned_data array element of the executing CPU: asm volatile("rdtsc" : "=A" (sched_data->last_schedule)); The context_swtch field of kstat is also increased by 1 to update the statistics maintained by the kernel: kstat.context_swtch++; It is also crucial to set up the address space of next properly. We know from Chapter 8 that the active_mm field of the process descriptor points to the memory descriptor that is effectively used by the process, while the mm field points to the memory descriptor owned by the process. For normal processes, the two fields hold the same address; however, a kernel thread does not have its own address space and its mm field is always set to NULL. The schedule( ) function ensures that if next is a kernel thread, then it uses the address space used by prev: if (!next->mm) { next->active_mm = prev->active_mm; atomic_inc(&prev->active_mm->mm_count); cpu_tlbstate[this_cpu].state == TLBSTATE_LAZY; } In earlier versions of Linux, kernel threads had their own address space. That design choice was suboptimal when the scheduler selected a kernel thread as a new process to run because changing the Page Tables was useless; since any kernel thread runs in Kernel Mode, it uses only the fourth gigabyte of the linear address space, whose mapping is the same for all processes in the system. Even worse, writing into the cr3 register invalidates all TLB entries (see Section 2.4.8), which leads to a significant performance penalty. Linux 2.4 is much more efficient because Page Tables aren't touched at all if next is a kernel thread. As further optimization, if next is a kernel thread, the schedule( ) function sets the process into lazy TLB mode (see Section 2.4.8). Conversely, if next is a regular process, the schedule( ) function replaces the address space of prev with the one of next: if (next->mm) switch_mm(prev->active_mm, next->mm, next, this_cpu); If prev is a kernel thread, the schedule( ) function releases the address space used by prev and resets prev->active_mm: if (!prev->mm) { mmdrop(prev->active_mm); prev->active_mm = NULL; } Recall that mmdrop( ) decrements the usage counter of the memory descriptor; if the counter reaches 0, it also frees the descriptor together with the associated Page Tables and virtual memory regions. Now schedule( ) can finally invoke switch_to( ) to perform the process switch between prev and next (see Section 3.3.3): switch_to(prev, next, prev); 11.2.2.4 Actions performed by schedule( ) after a process switch The instructions of the schedule( ) function following the switch_to macro invocation will not be performed right away by the next process, but at a later time by prev when the scheduler selects it again for execution. However, at that moment, the prev local variable does not point to our original process that was to be replaced when we started the description of schedule( ), but rather to the process that was replaced by our original prev when it was scheduled again. (If you are confused, go back and read Section 3.3.3.) The last instructions of the schedule( ) function are: _ _schedule_tail(prev); if (prev->lock_depth >= 0) spin_lock(&kernel_flag); if (current->need_resched) goto need_resched_back; return; As you see, schedule( ) invokes _ _schedule_tail( ) (described next), reacquires the global kernel lock if necessary, and checks whether some other process has set the need_resched field of prev while it was not running. In this case, the whole schedule( ) function is reexecuted from the beginning; otherwise, the function terminates. In uniprocessor systems, the _ _schedule_tail( ) function limits itself to clear the SCHED_YIELD flag of the policy field of prev. Conversely, in multiprocessor systems, the function executes code that is essentially equivalent to the following fragment: policy = prev->policy; prev->policy = policy & ~SCHED_YIELD; wmb( ); spin_lock(&prev->alloc_lock); prev->cpus_runnable = ~0UL; spin_lock_irqsave(&runqueue_lock, flags); if (prev->state == TASK_RUNNING && prev != init_task[smp_processor_id( )] && prev->cpus_runnable == ~0UL && !(policy & SCHED_YIELD)) reschedule_idle(prev); spin_unlock_irqrestore(&runqueue_lock, flags); spin_unlock(&prev->alloc_lock); The wmb( ) memory barrier is used to make sure that the processor won't reshuffle the assembly language instructions that modify the policy field with those that acquire the alloc_lock spin lock (see Section 5.3.2). As you may notice, the role of _ _schedule_tail( ) is far more important in multiprocessor systems because this function checks whether the process that was replaced can be rescheduled on some other CPU. This attempt is performed only if the following conditions are satisfied: ● prev is in TASK_RUNNING state. ● prev is not the swapper process of the executing CPU. ● The SCHED_YIELD flag of prev->policy was not set. ● prev was not already selected by another CPU in the time frame elapsed between the assignment to the cpus_runnable field and the if statement (the if statement itself is protected by the runqueue_lock spin lock; see the code shown in the previous section). To check whether the priority of prev is high enough to replace the current process of some other CPU, _ _schedule_tail( ) invokes reschedule_idle( ). This is the same function invoked by wake_up_process( ) and is described in the later section Section 11.2.2.6. The next two sections complete the analysis of the scheduler. They describe, respectively, the goodness( ) and reschedule_idle( ) functions. 11.2.2.5 How good is a runnable process? The heart of the scheduling algorithm includes identifying the best candidate among all processes in the runqueue list. This is what the goodness( ) function does. It receives as input parameters: ● p, the descriptor pointer of candidate process ● this_cpu, the logical number of the executing CPU ● this_mm, the memory descriptor address of the process being replaced The integer value weight returned by goodness( ) measures the "goodness" of p and has the following meanings: weight = -1 p is the prev process, and its SCHED_YIELD flag is set. The process will be selected only if no other runnable processes (beside the swapper processes) are included in the runqueue. weight = 0 p is a conventional process that has exhausted its quantum (p->counter is zero). Unless all runnable processes have also exhausted their quantum, it will not be selected for execution. 2 <= weight <= 77 p is a conventional process that has not exhausted its quantum. The weight is computed as follows: weight = p->counter + 20 - p->nice; if (p->processor == this_cpu) weight += 15; if (p->mm == this_mm || !p->mm) weight += 1; In multiprocessor systems, a large bonus (+ 15) is given to the process if it was last running on the CPU that is executing the scheduler. The bonus helps in reducing the number of transfers of processes across several CPUs during their executions, thus yielding a smaller number of hardware cache misses. The function also gives a small bonus (+ 1) to the process if it is a kernel thread or it shares the memory address space with the previously running process. Again, the process is favored mainly because the TLBs must not be invalidated by writing into the cr3 register. weight >= 1000 p is a real-time process. The weight is given by p->counter + 1000. 11.2.2.6 Scheduling on multiprocessor systems With respect to earlier versions, the Linux 2.4 scheduling algorithm has been improved to enhance its performance on multiprocessor systems. It was also simplified, which is a great improvement by itself. As we have seen, each processor runs the schedule( ) function on its own to replace the process that is currently in execution. However, processors are able to exchange information to boost system performance. In particular, right after a process switch, any processor usually checks whether the just replaced process should be executed on some other CPU running a lower priority process. This check is performed by reschedule_idle( ). The reschedule_idle( ) function looks for some other CPU to run the process p passed as parameter and uses interprocessor interrupts to force other CPUs to perform scheduling. The function performs a series of tests in a fixed order. If one of them is successful, the function sends a RESCHEDULE_VECTOR interprocessor interrupt to the selected CPU (see Section 4.6.2) and returns. If all tests fail, the function returns without forcing a rescheduling. The tests are performed in the following order: 1. Is the CPU that was last running p (i.e., the one having index p->processor) currently idle? best_cpu = p->processor; if ((p->cpus_allowed & p->cpus_runnable & (1 << best_cpu)) && cpu_curr(best_cpu) == init_tasks[best_cpu]) { send_now_idle: need_resched= init_tasks[best_cpu]->need_resched; init_tasks[best_cpu]->need_resched = 1; if (best_cpu != smp_processor_id( ) && !need_resched) smp_send_reschedule(best_cpu); } This is the best possible case because no process is to be preempted and the hardware cache of the processor is warm (filled with useful data). Notice that this case cannot happen when reschedule_idle( ) is invoked by the scheduler because schedule( ) never replaces a runnable process with the swapper kernel thread. This case may happen, however, when reschedule_idle( ) is invoked by wake_up_process( )—that is, when p has just been woken up. To force the rescheduling on the target processor, the need_resched field of the swapper kernel thread is set. If the target processor is different from the one executing the reschedule_idle( ) function, a RESCHEDULE_VECTOR interprocessor interrupt is also raised. In fact, the idle processor usually executes a halt assembly language instruction to save power, and it can be woken up only by an interrupt. It is also possible, however, to let the swapper kernel thread actively poll the need_resched field, waiting for its value to change from - 1 to +1, in order to speed up the rescheduling and avoid the interprocessor interrupt. This much more power- consuming algorithm can be activated by passing the "idle=poll" parameter to the kernel in the booting phase. 2. Does an idle processor exist that can execute p? oldest_idle = -1; for (cpu=0; cpucpus_allowed & p->cpus_runnable & (1 << cpu))) continue; if (cpu_curr(cpu) == init_tasks[cpu] && last_schedule(cpu) < oldest_idle) oldest_idle = last_schedule(cpu), target_tsk = cpu_curr(cpu); } if (oldest_idle != -1) { best_cpu = target_tsk->processor; goto send_now_idle; } Among the idle processors that can execute p, the function selects the least recently active. Recall that the Time Stamp Counter value of the last process switch of every CPU is stored in the aligned_data array (see the earlier section Section 11.2.1). Once the function finds the oldest idle CPU, the function jumps to the code already described in the previous case to force a rescheduling. The rationale behind the "oldest idle rule" is that this CPU is likely to have the greatest number of invalid hardware cache lines. 3. Does there exist a processor that can execute p and whose current process has lower dynamic priority than p? max_prio = 0; for (cpu=0; cpucpus_allowed & p->cpus_runnable & (1 << cpu))) continue; prio = goodness(p, cpu, cpu_curr(cpu)->active_mm) - goodness(cpu_curr(cpu), cpu, cpu_curr(cpu)->active_mm); if (prio > max_prio) max_prio = prio, target_tsk = cpu_curr(cpu); } if (max_prio > 0) { target_tsk->need_resched = 1; if (target_tsk->processor != smp_processor_id( )) smp_send_reschedule(target_tsk->processor); } reschedule_idle( ) finds the processor for which the difference between the goodness of replacing the current process with p and the goodness of replacing the current process with the current process itself is maximum. The function forces a rescheduling on the corresponding processor if the maximum is a positive value. Notice that the function doesn't simply look at the counter and nice fields of the processes; rather, it uses goodness( ), which takes into consideration the cost of replacing the currently running process with another process that potentially uses a different address space. The Hyper-threading Technology Very recently, Intel introduced the hyper-threading technology. Basically, a hyper-threaded CPU is a microprocessor that executes two threads of execution at once; it includes several copies of the internal registers and quickly switches between them. Thanks to this approach, the machine cycles spent when one thread is accessing the RAM can be exploited by the second thread. A hyper-threaded CPU is seen by the kernel as two different CPUs, so Linux does not have to be explicitly made aware of it. However, Linux breaks the "oldest idle rule" and forces an immediate rescheduling when it discovers that a hyper-threaded CPU is running two idle processes. 11.2.3 Performance of the Scheduling Algorithm The scheduling algorithm of Linux is both self-contained and relatively easy to follow. For this reason, many kernel hackers love to try to make improvements. However, the scheduler is a rather mysterious component of the kernel. While you can change its performance significantly by modifying just a few key parameters, there is usually no theoretical support to justify the results obtained. Furthermore, you can't be sure that the positive (or negative) results obtained will continue to hold when the mix of requests submitted by the users (real-time, interactive, I/O-bound, background, etc.) varies significantly. Actually, for almost every proposed scheduling strategy, it is possible to derive an artificial mix of requests that yields poor system performances. Let's try to outline some pitfalls of the Linux 2.4 scheduler. As it turns out, some of these limitations become significant on large systems with many users. On a single workstation that is running a few tens of processes at a time, the Linux 2.4 scheduler is quite efficient. 11.2.3.1 The algorithm does not scale well If the number of existing processes is very large, it is inefficient to recompute all dynamic priorities at once. In old traditional Unix kernels, the dynamic priorities were recomputed every second, so the problem was even worse. Linux tries instead to minimize the overhead of the scheduler. Priorities are recomputed only when all runnable processes have exhausted their time quantum. Therefore, when the number of processes is large, the recomputation phase is more expensive but executed less frequently. This simple approach has a disadvantage: when the number of runnable processes is very large, I/O- bound processes are seldom boosted, and therefore, interactive applications have a longer response time. 11.2.3.2 The predefined quantum is too large for high system loads The system responsiveness experienced by users depends heavily on the system load, which is the average number of processes that are runnable and thus waiting for CPU time.[6] [6] The uptime program returns the system load for the past 1, 5, and 15 minutes. The same information can be obtained by reading the /proc/loadavg file. As mentioned before, system responsiveness also depends on the average time-quantum duration of the runnable processes. In Linux, the predefined time quantum appears to be too large for high-end machines that have a very high expected system load. 11.2.3.3 I/O-bound process boosting strategy is not optimal The preference for I/O-bound processes is a good strategy to ensure a short response time for interactive programs, but it is not perfect. Indeed, some batch programs with almost no user interaction are I/O- bound. For instance, consider a database search engine that must typically read lots of data from the hard disk, or a network application that must collect data from a remote host on a slow link. Even if these kinds of processes do not need a short response time, they are boosted by the scheduling algorithm. On the other hand, interactive programs that are also CPU-bound may appear unresponsive to the users, since the increment of dynamic priority due to I/O blocking operations may not compensate for the decrement due to CPU usage. 11.2.3.4 Support for real-time applications is weak As stated in the first chapter, nonpreemptive kernels are not well suited for real-time applications, since processes may spend several milliseconds in Kernel Mode while handling an interrupt or exception. During this time, a real-time process that becomes runnable cannot be resumed. This is unacceptable for real- time applications, which require predictable and low response times.[7] [7] The Linux kernel has been modified in several ways so it can handle a few hard real-time jobs if they remain short. Basically, hardware interrupts are trapped and kernel execution is monitored by a kind of "superkernel." These changes do not make Linux a true real-time system, though. Future versions of Linux might address this problem, by either implementing SVR4's "fixed preemption points" or making the kernel fully preemptive. It remains questionable, however, whether these design choices are appropriate for a general-purpose operating systems such as Linux. Kernel preemption, in fact, is just one of several necessary conditions for implementing an effective real- time scheduler. Several other issues must be considered. For instance, real-time processes often must use resources that are also needed by conventional processes. A real-time process may thus end up waiting until a lower-priority process releases some resource. This phenomenon is called priority inversion. Moreover, a real-time process could require a kernel service that is granted on behalf of another lower- priority process (for example, a kernel thread). This phenomenon is called hidden scheduling. An effective real-time scheduler should address and resolve such problems. Luckily, all these shortcomings have been fixed in the brand new scheduler developed by Ingo Molnar that is included in the Linux 2.5 current development version. This scheduler is so efficient that it has been back-ported to Linux 2.4 and adopted by some commercial distributions of the GNU/Linux system. I l@ve RuBoard I l@ve RuBoard 11.3 System Calls Related to Scheduling Several system calls have been introduced to allow processes to change their priorities and scheduling policies. As a general rule, users are always allowed to lower the priorities of their processes. However, if they want to modify the priorities of processes belonging to some other user or if they want to increase the priorities of their own processes, they must have superuser privileges. 11.3.1 The nice( ) System Call The nice( )[8] system call allows processes to change their base priority. The integer value contained in the increment parameter is used to modify the nice field of the process descriptor. The nice Unix command, which allows users to run programs with modified scheduling priority, is based on this system call. [8] Since this system call is usually invoked to lower the priority of a process, users who invoke it for their processes are "nice" to other users. The sys_nice( ) service routine handles the nice( ) system call. Although the increment parameter may have any value, absolute values larger than 40 are trimmed down to 40. Traditionally, negative values correspond to requests for priority increments and require superuser privileges, while positive ones correspond to requests for priority decrements. In the case of a negative increment, the function invokes the capable( ) function to verify whether the process has a CAP_SYS_NICE capability. We discuss that function, together with the notion of capability, in Chapter 20. If the user turns out to have the capability required to change priorities, sys_nice( ) adds the value of increment to the nice field of current. If necessary, the value of this field is trimmed down so it won't be less than - 20 or greater than + 19. The nice( ) system call is maintained for backward compatibility only; it has been replaced by the setpriority( ) system call described next. 11.3.2 The getpriority( ) and setpriority( ) System Calls The nice( ) system call affects only the process that invokes it. Two other system calls, denoted as getpriority( ) and setpriority( ), act on the base priorities of all processes in a given group. getpriority( ) returns 20 minus the lowest nice field value among all processes in a given group—that is, the highest priority among that processes; setpriority( ) sets the base priority of all processes in a given group to a given value. The kernel implements these system calls by means of the sys_getpriority( ) and sys_setpriority( ) service routines. Both of them act essentially on the same group of parameters: which The value that identifies the group of processes; it can assume one of the following: PRIO_PROCESS Selects the processes according to their process ID (pid field of the process descriptor). PRIO_PGRP Selects the processes according to their group ID (pgrp field of the process descriptor). PRIO_USER Selects the processes according to their user ID (uid field of the process descriptor). who The value of the pid, pgrp, or uid field (depending on the value of which) to be used for selecting the processes. If who is 0, its value is set to that of the corresponding field of the current process. niceval The new base priority value (needed only by sys_setpriority( )). It should range between - 20 (highest priority) and + 19 (lowest priority). As stated before, only processes with a CAP_SYS_NICE capability are allowed to increase their own base priority or to modify that of other processes. As we saw in Chapter 9, system calls return a negative value only if some error occurred. For this reason, getpriority( ) does not return a normal nice value ranging between - 20 and + 19, but rather a nonnegative value ranging between 1 and 40. 11.3.3 System Calls Related to Real-Time Processes We now introduce a group of system calls that allow processes to change their scheduling discipline and, in particular, to become real-time processes. As usual, a process must have a CAP_SYS_NICE capability to modify the values of the rt_priority and policy process descriptor fields of any process, including itself. 11.3.3.1 The sched_getscheduler( ) and sched_setscheduler( ) system calls The sched_ getscheduler( ) system call queries the scheduling policy currently applied to the process identified by the pid parameter. If pid equals 0, the policy of the calling process is retrieved. On success, the system call returns the policy for the process: SCHED_FIFO, SCHED_RR, or SCHED_OTHER. The corresponding sys_sched_getscheduler( ) service routine invokes find_process_by_pid( ), which locates the process descriptor corresponding to the given pid and returns the value of its policy field. The sched_setscheduler( ) system call sets both the scheduling policy and the associated parameters for the process identified by the parameter pid. If pid is equal to 0, the scheduler parameters of the calling process will be set. The corresponding sys_sched_setscheduler( ) function checks whether the scheduling policy specified by the policy parameter and the new static priority specified by the param- >sched_priority parameter are valid. It also checks whether the process has CAP_SYS_NICE capability or whether its owner has superuser rights. If everything is OK, it executes the following statements: p->policy = policy; p->rt_priority = param->sched_priority; if (task_on_runqueue(p)) move_first_runqueue(p); current->need_resched = 1; 11.3.3.2 The sched_ getparam( ) and sched_setparam( ) system calls The sched_getparam( ) system call retrieves the scheduling parameters for the process identified by pid. If pid is 0, the parameters of the current process are retrieved. The corresponding sys_sched_getparam( ) service routine, as one would expect, finds the process descriptor pointer associated with pid, stores its rt_priority field in a local variable of type sched_param, and invokes copy_to_user( ) to copy it into the process address space at the address specified by the param parameter. The sched_setparam( ) system call is similar to sched_setscheduler( ). The difference is that sched_setscheduler( ) does not let the caller set the policy field's value.[9] The corresponding sys_sched_setparam( ) service routine is almost identical to sys_sched_setscheduler( ), but the policy of the affected process is never changed. [9] This anomaly is caused by a specific requirement of the POSIX standard. 11.3.3.3 The sched_ yield( ) system call The sched_ yield( ) system call allows a process to relinquish the CPU voluntarily without being suspended; the process remains in a TASK_RUNNING state, but the scheduler puts it at the end of the runqueue list. In this way, other processes that have the same dynamic priority have a chance to run. The call is used mainly by SCHED_FIFO processes. The corresponding sys_sched_ yield( ) service routine checks first if there is some process in the system that is runnable, other than the process executing the system call and the swapper kernel threads. If there is no such process, sched_yield( ) returns without performing any action because no process would be able to use the freed processor. Otherwise, the function executes the following statements: if (current->policy == SCHED_OTHER) current->policy |= SCHED_YIELD; current->need_resched = 1; spin_lock_irq(&runqueue_lock); move_last_runqueue(current); spin_unlock_irq(&runqueue_lock); As a result, schedule( ) is invoked when returning from the sys_sched_ yield( ) service routine (see Section 4.8), and the current process will most likely be replaced. 11.3.3.4 The sched_ get_priority_min( ) and sched_ get_priority_max( ) system calls The sched_get_priority_min( ) and sched_get_priority_max( ) system calls return, respectively, the minimum and the maximum real-time static priority value that can be used with the scheduling policy identified by the policy parameter. The sys_sched_get_priority_min( ) service routine returns 1 if current is a real- time process, 0 otherwise. The sys_sched_get_priority_max( ) service routine returns 99 (the highest priority) if current is a real-time process, 0 otherwise. 11.3.3.5 The sched_rr_ get_interval( ) system call The sched_rr_get_interval( ) system writes in a structure stored in the User Mode address space the Round Robin time quantum for the real-time process identified by the pid parameter. If pid is zero, the system call writes the time quantum of the current process. The corresponding sys_sched_rr_get_interval( ) service routine invokes, as usual, find_process_by_pid( ) to retrieve the process descriptor associated with pid. It then converts the number of ticks stored in the nice field of the selected process descriptor into seconds and nanoseconds and copies the numbers into the User Mode structure. I l@ve RuBoard I l@ve RuBoard Chapter 12. The Virtual Filesystem One of Linux's keys to success is its ability to coexist comfortably with other systems. You can transparently mount disks or partitions that host file formats used by Windows, other Unix systems, or even systems with tiny market shares like the Amiga. Linux manages to support multiple disk types in the same way other Unix variants do, through a concept called the Virtual Filesystem. The idea behind the Virtual Filesystem is to put a wide range of information in the kernel to represent many different types of filesystems; there is a field or function to support each operation provided by any real filesystem supported by Linux. For each read, write, or other function called, the kernel substitutes the actual function that supports a native Linux filesystem, the NT filesystem, or whatever other filesystem the file is on. This chapter discusses the aims, structure, and implementation of Linux's Virtual Filesystem. It focuses on three of the five standard Unix file types—namely, regular files, directories, and symbolic links. Device files are covered in Chapter 13, while pipes are discussed in Chapter 19. To show how a real filesystem works, Chapter 17 covers the Second Extended Filesystem that appears on nearly all Linux systems. I l@ve RuBoard I l@ve RuBoard 12.1 The Role of the Virtual Filesystem (VFS) The Virtual Filesystem (also known as Virtual Filesystem Switch or VFS) is a kernel software layer that handles all system calls related to a standard Unix filesystem. Its main strength is providing a common interface to several kinds of filesystems. For instance, let's assume that a user issues the shell command: $ cp /floppy/TEST /tmp/test where /floppy is the mount point of an MS-DOS diskette and /tmp is a normal Second Extended Filesystem (Ext2) directory. As shown in Figure 12-1(a), the VFS is an abstraction layer between the application program and the filesystem implementations. Therefore, the cp program is not required to know the filesystem types of /floppy/TEST and /tmp/test. Instead, cp interacts with the VFS by means of generic system calls known to anyone who has done Unix programming (see Section 1.5.6); the code executed by cp is shown in Figure 12-1(b). Figure 12-1. VFS role in a simple file copy operation Filesystems supported by the VFS may be grouped into three main classes: Disk-based filesystems These manage the memory space available in a local disk partition. Some of the well- known disk-based filesystems supported by the VFS are: ❍ Filesystems for Linux such as the widely used Second Extended Filesystem (Ext2), the recent Third Extended Filesystem (Ext3), and the Reiser Filesystems (ReiserFS)[1] [1] Although these filesystems owe their birth to Linux, they have been ported to several other operating systems. ❍ Filesystems for Unix variants such as SYSV filesystem (System V, Coherent, XENIX), UFS (BSD, Solaris, Next), MINIX filesystem, and VERITAS VxFS (SCO UnixWare) ❍ Microsoft filesystems such as MS-DOS, VFAT (Windows 95 and later releases), and NTFS (Windows NT) ❍ ISO9660 CD-ROM filesystem (formerly High Sierra Filesystem) and Universal Disk Format (UDF) DVD filesystem ❍ Other proprietary filesystems such as IBM's OS/2 (HPFS), Apple's Macintosh (HFS), Amiga's Fast Filesystem (AFFS), and Acorn Disk Filing System (ADFS) ❍ Additional journaling file systems originating in systems other than Linux such as IBM's JFS and SGI's XFS. Network filesystems These allow easy access to files included in filesystems belonging to other networked computers. Some well-known network filesystems supported by the VFS are NFS, Coda, AFS (Andrew filesystem), SMB (Server Message Block, used in Microsoft Windows and IBM OS/2 LAN Manager to share files and printers), and NCP (Novell's NetWare Core Protocol). Special filesystems (also called virtual filesystems) These do not manage disk space, either locally or remotely. The /proc filesystem is a typical example of a special filesystem (see the later section Section 12.3.1). In this book, we describe in detail the Ext2 and Ext3 filesystems only (see Chapter 17); the other filesystems are not covered for lack of space. As mentioned in Section 1.5, Unix directories build a tree whose root is the / directory. The root directory is contained in the root filesystem, which in Linux, is usually of type Ext2. All other filesystems can be "mounted" on subdirectories of the root filesystem.[2] [2] When a filesystem is mounted on a directory, the contents of the directory in the parent filesystem are no longer accessible, since any pathname, including the mount point, will refer to the mounted filesystem. However, the original directory's content shows up again when the filesystem is unmounted. This somewhat surprising feature of Unix filesystems is used by system administrators to hide files; they simply mount a filesystem on the directory containing the files to be hidden. A disk-based filesystem is usually stored in a hardware block device like a hard disk, a floppy, or a CD-ROM. A useful feature of Linux's VFS allows it to handle virtual block devices like /dev/loop0, which may be used to mount filesystems stored in regular files. As a possible application, a user may protect his own private filesystem by storing an encrypted version of it in a regular file. The first Virtual Filesystem was included in Sun Microsystems's SunOS in 1986. Since then, most Unix filesystems include a VFS. Linux's VFS, however, supports the widest range of filesystems. 12.1.1 The Common File Model The key idea behind the VFS consists of introducing a common file model capable of representing all supported filesystems. This model strictly mirrors the file model provided by the traditional Unix filesystem. This is not surprising, since Linux wants to run its native filesystem with minimum overhead. However, each specific filesystem implementation must translate its physical organization into the VFS's common file model. For instance, in the common file model, each directory is regarded as a file, which contains a list of files and other directories. However, several non-Unix disk-based filesystems use a File Allocation Table (FAT), which stores the position of each file in the directory tree. In these filesystems, directories are not files. To stick to the VFS's common file model, the Linux implementations of such FAT-based filesystems must be able to construct on the fly, when needed, the files corresponding to the directories. Such files exist only as objects in kernel memory. More essentially, the Linux kernel cannot hardcode a particular function to handle an operation such as read( ) or ioctl( ). Instead, it must use a pointer for each operation; the pointer is made to point to the proper function for the particular filesystem being accessed. Let's illustrate this concept by showing how the read( ) shown in Figure 12-1 would be translated by the kernel into a call specific to the MS-DOS filesystem. The application's call to read( ) makes the kernel invoke the corresponding sys_read( ) service routine, just like any other system call. The file is represented by a file data structure in kernel memory, as we shall see later in this chapter. This data structure contains a field called f_op that contains pointers to functions specific to MS-DOS files, including a function that reads a file. sys_read( ) finds the pointer to this function and invokes it. Thus, the application's read( ) is turned into the rather indirect call: file->f_op->read(...); Similarly, the write( ) operation triggers the execution of a proper Ext2 write function associated with the output file. In short, the kernel is responsible for assigning the right set of pointers to the file variable associated with each open file, and then for invoking the call specific to each filesystem that the f_op field points to. One can think of the common file model as object-oriented, where an object is a software construct that defines both a data structure and the methods that operate on it. For reasons of efficiency, Linux is not coded in an object-oriented language like C++. Objects are therefore implemented as data structures with some fields pointing to functions that correspond to the object's methods. The common file model consists of the following object types: The superblock object Stores information concerning a mounted filesystem. For disk-based filesystems, this object usually corresponds to a filesystem control block stored on disk. The inode object Stores general information about a specific file. For disk-based filesystems, this object usually corresponds to a file control block stored on disk. Each inode object is associated with an inode number, which uniquely identifies the file within the filesystem. The file object Stores information about the interaction between an open file and a process. This information exists only in kernel memory during the period when each process accesses a file. The dentry object Stores information about the linking of a directory entry with the corresponding file. Each disk-based filesystem stores this information in its own particular way on disk. Figure 12-2 illustrates with a simple example how processes interact with files. Three different processes have opened the same file, two of them using the same hard link. In this case, each of the three processes uses its own file object, while only two dentry objects are required—one for each hard link. Both dentry objects refer to the same inode object, which identifies the superblock object and, together with the latter, the common disk file. Figure 12-2. Interaction between processes and VFS objects Besides providing a common interface to all filesystem implementations, the VFS has another important role related to system performance. The most recently used dentry objects are contained in a disk cache named the dentry cache, which speeds up the translation from a file pathname to the inode of the last pathname component. Generally speaking, a disk cache is a software mechanism that allows the kernel to keep in RAM some information that is normally stored on a disk, so that further accesses to that data can be quickly satisfied without a slow access to the disk itself.[3] Beside the dentry cache, Linux uses other disk caches, like the buffer cache and the page cache, which are described in forthcoming chapters. [3] Notice how a disk cache differs from a hardware cache or a memory cache, neither of which has anything to do with disks or other devices. A hardware cache is a fast static RAM that speeds up requests directed to the slower dynamic RAM (see Section 2.4.7). A memory cache is a software mechanism introduced to bypass the Kernel Memory Allocator (see Section 7.2.1). 12.1.2 System Calls Handled by the VFS Table 12-1 illustrates the VFS system calls that refer to filesystems, regular files, directories, and symbolic links. A few other system calls handled by the VFS, such as ioperm( ), ioctl( ), pipe( ), and mknod( ), refer to device files and pipes. These are discussed in later chapters. A last group of system calls handled by the VFS, such as socket( ), connect( ), bind( ), and protocols( ), refer to sockets and are used to implement networking; some of them are discussed in Chapter 18. Some of the kernel service routines that correspond to the system calls listed in Table 12-1 are discussed either in this chapter or in Chapter 17. Table 12-1. Some system calls handled by the VFS System call name Description mount( ) umount( ) Mount/unmount filesystems sysfs( ) Get filesystem information statfs( ) fstatfs( ) ustat( ) Get filesystem statistics chroot( ) pivot_root( ) Change root directory chdir( ) fchdir( ) getcwd( ) Manipulate current directory mkdir( ) rmdir( ) Create and destroy directories getdents( ) readdir( ) link( ) unlink( ) rename( ) Manipulate directory entries readlink( ) symlink( ) Manipulate soft links chown( ) fchown( ) lchown( ) Modify file owner chmod( ) fchmod( ) utime( ) Modify file attributes stat( ) fstat( ) lstat( ) access( ) Read file status open( ) close( ) creat( ) umask( ) Open and close files dup( ) dup2( ) fcntl( ) Manipulate file descriptors select( ) poll( ) Asynchronous I/O notification truncate( ) ftruncate( ) Change file size lseek( ) _llseek( ) Change file pointer read( ) write( ) readv( ) writev( ) sendfile( ) readahead( ) Carry out file I/O operations pread( ) pwrite( ) Seek file and access it mmap( ) munmap( ) madvise( ) mincore( ) Handle file memory mapping fdatasync( ) fsync( ) sync( ) msync( ) Synchronize file data flock( ) Manipulate file lock We said earlier that the VFS is a layer between application programs and specific filesystems. However, in some cases, a file operation can be performed by the VFS itself, without invoking a lower-level procedure. For instance, when a process closes an open file, the file on disk doesn't usually need to be touched, and hence the VFS simply releases the corresponding file object. Similarly, when the lseek( ) system call modifies a file pointer, which is an attribute related to the interaction between an opened file and a process, the VFS needs to modify only the corresponding file object without accessing the file on disk and therefore does not have to invoke a specific filesystem procedure. In some sense, the VFS could be considered a "generic" filesystem that relies, when necessary, on specific ones. I l@ve RuBoard I l@ve RuBoard 12.2 VFS Data Structures Each VFS object is stored in a suitable data structure, which includes both the object attributes and a pointer to a table of object methods. The kernel may dynamically modify the methods of the object and, hence, it may install specialized behavior for the object. The following sections explain the VFS objects and their interrelationships in detail. 12.2.1 Superblock Objects A superblock object consists of a super_block structure whose fields are described in Table 12-2. Table 12-2. The fields of the superblock object Type Field Description struct list_head s_list Pointers for superblock list kdev_t s_dev Device identifier unsigned long s_blocksize Block size in bytes unsigned char s_blocksize_bits Block size in number of bits unsigned char s_dirt Modified (dirty) flag unsigned long long s_maxbytes Maximum size of the files struct file_system_type * s_type Filesystem type struct super_operations * s_op Superblock methods struct dquot_operations * dq_op Disk quota methods unsigned long s_flags Mount flags unsigned long s_magic Filesystem magic number struct dentry * s_root Dentry object of mount directory struct rw_semaphore s_umount Semaphore used for unmounting struct semaphore s_lock Superblock semaphore int s_count Reference counter atomic_t s_active Secondary reference counter struct list_head s_dirty List of modified inodes struct list_head s_locked_inodes List of inodes involved in I/O struct list_head s_files List of file objects assigned to the superblock struct block_device * s_bdev Pointer to the block device driver descriptor struct list_head s_instances Pointers for a list of superblock objects of a given filesystem type (see Section 12.3.2) struct quota_mount_options s_dquot Options for disk quota union u Specific filesystem information All superblock objects are linked in a circular doubly linked list. The first element of this list is represented by the super_blocks variable, while the s_list field of the superblock object stores the pointers to the adjacent elements in the list. The sb_lock spin lock protects the list against concurrent accesses in multiprocessor systems. The last u union field includes superblock information that belongs to a specific filesystem; for instance, as we shall see later in Chapter 17, if the superblock object refers to an Ext2 filesystem, the field stores an ext2_sb_info structure, which includes the disk allocation bit masks and other data of no concern to the VFS common file model. In general, data in the u field is duplicated in memory for reasons of efficiency. Any disk- based filesystem needs to access and update its allocation bitmaps in order to allocate or release disk blocks. The VFS allows these filesystems to act directly on the u union field of the superblock in memory without accessing the disk. This approach leads to a new problem, however: the VFS superblock might end up no longer synchronized with the corresponding superblock on disk. It is thus necessary to introduce an s_dirt flag, which specifies whether the superblock is dirty—that is, whether the data on the disk must be updated. The lack of synchronization leads to the familiar problem of a corrupted filesystem when a site's power goes down without giving the user the chance to shut down a system cleanly. As we shall see in Section 14.2.4, Linux minimizes this problem by periodically copying all dirty superblocks to disk. The methods associated with a superblock are called superblock operations. They are described by the super_operations structure whose address is included in the s_op field. Each specific filesystem can define its own superblock operations. When the VFS needs to invoke one of them, say read_inode( ), it executes the following: sb->s_op->read_inode(inode); where sb stores the address of the superblock object involved. The read_inode field of the super_operations table contains the address of the suitable function, which is therefore directly invoked. Let's briefly describe the superblock operations, which implement higher-level operations like deleting files or mounting disks. They are listed in the order they appear in the super_operations table: read_inode(inode) Fills the fields of the inode object whose address is passed as the parameter from the data on disk; the i_ino field of the inode object identifies the specific filesystem inode on the disk to be read. read_inode2(inode, p) Similar to the previous one, but the inode is identified by a 64-bit number pointed by p. This method should disappear as soon as the whole VFS architecture moves to 64- bit quantities; for now, it is used by the ReiserFS filesystem only. dirty_inode(inode) Invoked when the inode is marked as modified (dirty). Used by filesystems like ReiserFS and Ext3 to update the filesystem journal on disk. write_inode(inode, flag) Updates a filesystem inode with the contents of the inode object passed as the parameter; the i_ino field of the inode object identifies the filesystem inode on disk that is concerned. The flag parameter indicates whether the I/O operation should be synchronous. put_inode(inode) Releases the inode object whose address is passed as the parameter. As usual, releasing an object does not necessarily mean freeing memory, since other processes may still use that object. delete_inode(inode) Deletes the data blocks containing the file, the disk inode, and the VFS inode. put_super(super) Releases the superblock object whose address is passed as the parameter (because the corresponding filesystem is unmounted). write_super(super) Updates a filesystem superblock with the contents of the object indicated. write_super_lockfs(super) Blocks changes to the filesystem and updates the superblock with the contents of the object indicated. The method should be implemented by journaling filesystems, and should be invoked by the Logical Volume Manager (LVM) driver. It is currently not in use. unlockfs(super) Undoes the block of filesystem updates achieved by the write_super_lockfs( ) superblock method. statfs(super, buf) Returns statistics on a filesystem by filling the buf buffer. remount_fs(super, flags, data) Remounts the filesystem with new options (invoked when a mount option must be changed). clear_inode(inode) Like put_inode, but also releases all pages that contain data concerning the file that corresponds to the indicated inode. umount_begin(super) Interrupts a mount operation because the corresponding unmount operation has been started (used only by network filesystems). fh_to_dentry(super, filehandle, len, filehandletype. parent) Used by the Network File System (NFS) kernel thread knfsd to return the dentry object corresponding to a given file handle. (A file handle is an identifier of a NFS file.) dentry_to_fh(dentry, filehandle, lenp, need_parent) Used by the NFS kernel thread knfsd to derive the file handle corresponding to a given dentry object. show_options(seq_file, vfsmount) Used to display the filesystem-specific options The preceding methods are available to all possible filesystem types. However, only a subset of them applies to each specific filesystem; the fields corresponding to unimplemented methods are set to NULL. Notice that no read_super method to read a superblock is defined—how could the kernel invoke a method of an object yet to be read from disk? We'll find the read_super method in another object describing the filesystem type (see the later section Section 12.4). 12.2.2 Inode Objects All information needed by the filesystem to handle a file is included in a data structure called an inode. A filename is a casually assigned label that can be changed, but the inode is unique to the file and remains the same as long as the file exists. An inode object in memory consists of an inode structure whose fields are described in Table 12-3. Table 12-3. The fields of the inode object Type Field Description struct list_head i_hash Pointers for the hash list struct list_head i_list Pointers for the inode list struct list_head i_dentry Pointers for the dentry list struct list_head i_dirty_buffers Pointers for the modified buffers list struct list_head i_dirty_data_buffers Pointers for the modified data buffers list unsigned long i_ino inode number unsigned int i_count Usage counter kdev_t i_dev Device identifier umode_t i_mode File type and access rights nlink_t i_nlink Number of hard links uid_t i_uid Owner identifier gid_t i_gid Group identifier kdev_t i_rdev Real device identifier off_t i_size File length in bytes time_t i_atime Time of last file access time_t i_mtime Time of last file write time_t i_ctime Time of last inode change unsigned int i_blkbits Block size in number of bits unsigned long i_blksize Block size in bytes unsigned long i_blocks Number of blocks of the file unsigned long i_version Version number, automatically incremented after each use struct semaphore i_sem inode semaphore struct semaphore i_zombie Secondary inode semaphore used when removing or renaming the inode struct inode_operations * i_op inode operations struct file_operations * i_fop Default file operations struct super_block * i_sb Pointer to superblock object wait_queue_head_t i_wait inode wait queue struct file_lock * i_flock Pointer to file lock list struct address_space * i_mapping Pointer to an address_space object (see Chapter 14) struct address_space i_data address_space object for block device file struct dquot ** i_dquot inode disk quotas struct list_head i_devices Pointers of a list of block device file inodes (see Chapter 13) struct pipe_inode_info * i_pipe Used if the file is a pipe (see Chapter 19) struct block_device * i_bdev Pointer to the block device driver struct char_device * i_cdev Pointer to the character device driver unsigned long i_dnotify_mask Bit mask of directory notify events struct dnotify_struct * i_dnotify Used for directory notifications unsigned long i_state inode state flags unsigned int i_flags Filesystem mount flags unsigned char i_sock Nonzero if file is a socket atomic_t i_writecount Usage counter for writing processes unsigned int i_attr_flags File creation flags _ _u32 i_generation inode version number (used by some filesystems) union u Specific filesystem information The final u union field is used to include inode information that belongs to a specific filesystem. For instance, as we shall see in Chapter 17, if the inode object refers to an Ext2 file, the field stores an ext2_inode_info structure. Each inode object duplicates some of the data included in the disk inode—for instance, the number of blocks allocated to the file. When the value of the i_state field is equal to I_DIRTY_SYNC, I_DIRTY_DATASYNC, or I_DIRTY_PAGES, the inode is dirty—that is, the corresponding disk inode must be updated; the I_DIRTY macro can be used to check the value of these three flags at once (see later for details). Other values of the i_state field are I_LOCK (the inode object is involved in a I/O transfer), I_FREEING (the inode object is being freed), and I_CLEAR (the inode object contents are no longer meaningful). Each inode object always appears in one of the following circular doubly linked lists: ● The list of valid unused inodes, typically those mirroring valid disk inodes and not currently used by any process. These inodes are not dirty and their i_count field is set to 0. The first and last elements of this list are referenced by the next and prev fields, respectively, of the inode_unused variable. This list acts as a disk cache. ● The list of in-use inodes, typically those mirroring valid disk inodes and used by some process. These inodes are not dirty and their i_count field is positive. The first and last elements are referenced by the inode_in_use variable. ● The list of dirty inodes. The first and last elements are referenced by the s_dirty field of the corresponding superblock object. Each of the lists just mentioned links the i_list fields of the proper inode objects. inode objects are also included in a hash table named inode_hashtable. The hash table speeds up the search of the inode object when the kernel knows both the inode number and the address of the superblock object corresponding to the filesystem that includes the file.[4] Since hashing may induce collisions, the inode object includes an i_hash field that contains a backward and a forward pointer to other inodes that hash to the same position; this field creates a doubly linked list of those inodes. The hash table also includes a special chain list for the inodes not assigned to a superblock (such as the inodes used by sockets; see Chapter 18); its first and last elements are referenced by the anon_hash_chain variable. [4] Actually, a Unix process may open a file and then unlink it. The i_nlink field of the inode could become 0, yet the process is still able to act on the file. In this particular case, the inode is removed from the hash table, even if it still belongs to the in-use or dirty list. The methods associated with an inode object are also called inode operations. They are described by an inode_operations structure, whose address is included in the i_op field. Here are the inode operations in the order they appear in the inode_operations table: create(dir, dentry, mode) Creates a new disk inode for a regular file associated with a dentry object in some directory. lookup(dir, dentry) Searches a directory for an inode corresponding to the filename included in a dentry object. link(old_dentry, dir, new_dentry) Creates a new hard link that refers to the file specified by old_dentry in the directory dir; the new hard link has the name specified by new_dentry. unlink(dir, dentry) Removes the hard link of the file specified by a dentry object from a directory. symlink(dir, dentry, symname) Creates a new inode for a symbolic link associated with a dentry object in some directory. mkdir(dir, dentry, mode) Creates a new inode for a directory associated with a dentry object in some directory. rmdir(dir, dentry) Removes from a directory the subdirectory whose name is included in a dentry object. mknod(dir, dentry, mode, rdev) Creates a new disk inode for a special file associated with a dentry object in some directory. The mode and rdev parameters specify, respectively, the file type and the device's major number. rename(old_dir, old_dentry, new_dir, new_dentry) Moves the file identified by old_entry from the old_dir directory to the new_dir one. The new filename is included in the dentry object that new_dentry points to. readlink(dentry, buffer, buflen) Copies into a memory area specified by buffer the file pathname corresponding to the symbolic link specified by the dentry. follow_link(inode, dir) Translates a symbolic link specified by an inode object; if the symbolic link is a relative pathname, the lookup operation starts from the specified directory. truncate(inode) Modifies the size of the file associated with an inode. Before invoking this method, it is necessary to set the i_size field of the inode object to the required new size. permission(inode, mask) Checks whether the specified access mode is allowed for the file associated with inode. revalidate(dentry) Updates the cached attributes of a file specified by a dentry object (usually invoked by the network filesystem). setattr(dentry, iattr) Notifies a "change event" after touching the inode attributes. getattr(dentry, iattr) Used by networking filesystems when noticing that some cached inode attributes must be refreshed. The methods just listed are available to all possible inodes and filesystem types. However, only a subset of them applies to a specific inode and filesystem; the fields corresponding to unimplemented methods are set to NULL. 12.2.3 File Objects A file object describes how a process interacts with a file it has opened. The object is created when the file is opened and consists of a file structure, whose fields are described in Table 12-4. Notice that file objects have no corresponding image on disk, and hence no "dirty" field is included in the file structure to specify that the file object has been modified. Table 12-4. The fields of the file object Type Field Description struct list_head f_list Pointers for generic file object list struct dentry * f_dentry dentry object associated with the file struct vfsmount * f_vfsmnt Mounted filesystem containing the file struct file_operations * f_op Pointer to file operation table atomic_t f_count File object's usage counter unsigned int f_flags Flags specified when opening the file mode_t f_mode Process access mode loff_t f_pos Current file offset (file pointer) unsigned long f_reada Read-ahead flag unsigned long f_ramax Maximum number of pages to be read- ahead unsigned long f_raend File pointer after last read-ahead unsigned long f_ralen Number of read-ahead bytes unsigned long f_rawin Number of read-ahead pages struct fown_struct f_owner Data for asynchronous I/O via signals unsigned int f_uid User's UID unsigned int f_gid User's GID int f_error Error code for network write operation unsigned long f_version Version number, automatically incremented after each use void * private_data Needed for tty driver struct kiobuf * f_iobuf Descriptor for direct access buffer (see Section 15.2) long f_iobuf_lock Lock for direct I/O transfer The main information stored in a file object is the file pointer—the current position in the file from which the next operation will take place. Since several processes may access the same file concurrently, the file pointer cannot be kept in the inode object. Each file object is always included in one of the following circular doubly linked lists: ● The list of "unused" file objects. This list acts both as a memory cache for the file objects and as a reserve for the superuser; it allows the superuser to open a file even if the dynamic memory in the system is exhausted. Since the objects are unused, their f_count fields are 0. The first element of the list is a dummy and it is stored in the free_list variable. The kernel makes sure that the list always contains at least NR_RESERVED_FILES objects, usually 10. ● The list of "in use" file objects not yet assigned to a superblock. The f_count field of each element in this list is set to 1. The first element of the list is a dummy and it is stored in the anon_list variable. ● Several lists of "in use" file objects already assigned to superblocks. Each superblock object stores in the s_files field the dummy first element of a list of file objects; thus, file objects of files belonging to different filesystems are included in different lists. The f_count field of each element in such a list is set to 1 plus the number of processes that are using the file object. Regardless of which list a file object is in at the moment, the pointers of the next and previous elements in the list are stored in the f_list field of the file object. The files_lock semaphore protects the lists against concurrent accesses in multiprocessor systems. The size of the list of "unused" file objects is stored in the nr_free_files field of the files_stat variable. The get_empty_filp( ) function is invoked when the VFS must allocate a new file object. The function checks whether the "unused" list has more than NR_RESERVED_FILES items, in which case one can be used for the newly opened file. Otherwise, it falls back to normal memory allocation. The files_stat variable also includes the nr_files field (which stores the number of file objects included in all lists) and the max_files field (which is the maximum number of allocatable file objects—i.e., the maximum number of files that can be accessed at the same time in the system).[5] [5] By default, max_files stores the value 8,192, but the system administrator can tune this parameter by writing into the /proc/sys/fs/file-max file. As we explained earlier in Section 12.1.1, each filesystem includes its own set of file operations that perform such activities as reading and writing a file. When the kernel loads an inode into memory from disk, it stores a pointer to these file operations in a file_operations structure whose address is contained in the i_fop field of the inode object. When a process opens the file, the VFS initializes the f_op field of the new file object with the address stored in the inode so that further calls to file operations can use these functions. If necessary, the VFS may later modify the set of file operations by storing a new value in f_op. The following list describes the file operations in the order in which they appear in the file_operations table: llseek(file, offset, origin) Updates the file pointer. read(file, buf, count, offset) Reads count bytes from a file starting at position *offset; the value *offset (which usually corresponds to the file pointer) is then incremented. write(file, buf, count, offset) Writes count bytes into a file starting at position *offset; the value *offset (which usually corresponds to the file pointer) is then incremented. readdir(dir, dirent, filldir) Returns the next directory entry of a directory in dirent; the filldir parameter contains the address of an auxiliary function that extracts the fields in a directory entry. poll(file, poll_table) Checks whether there is activity on a file and goes to sleep until something happens on it. ioctl(inode, file, cmd, arg) Sends a command to an underlying hardware device. This method applies only to device files. mmap(file, vma) Performs a memory mapping of the file into a process address space (see Chapter 15). open(inode, file) Opens a file by creating a new file object and linking it to the corresponding inode object (see Section 12.6.1 later in this chapter). flush(file) Called when a reference to an open file is closed—that is, when the f_count field of the file object is decremented. The actual purpose of this method is filesystem- dependent. release(inode, file) Releases the file object. Called when the last reference to an open file is closed—that is, when the f_count field of the file object becomes 0. fsync(file, dentry) Writes all cached data of the file to disk. fasync(fd, file, on) Enables or disables asynchronous I/O notification by means of signals. lock(file, cmd, file_lock) Applies a lock to the file (see Section 12.7 later in this chapter). readv(file, vector, count, offset) Reads bytes from a file and puts the results in the buffers described by vector; the number of buffers is specified by count. writev(file, vector, count, offset) Writes bytes into a file from the buffers described by vector; the number of buffers is specified by count. sendpage(file, page, offset, size, pointer, fill) Transfers data from this file to another file; this method is used by sockets (see Chapter 18). get_unmapped_area(file, addr, len, offset, flags) Gets an unused address range to map the file (used for frame buffer memory mappings). The methods just described are available to all possible file types. However, only a subset of them apply to a specific file type; the fields corresponding to unimplemented methods are set to NULL. 12.2.4 dentry Objects We mentioned in Section 12.1.1 that the VFS considers each directory a file that contains a list of files and other directories. We shall discuss in Chapter 17 how directories are implemented on a specific filesystem. Once a directory entry is read into memory, however, it is transformed by the VFS into a dentry object based on the dentry structure, whose fields are described in Table 12-5. The kernel creates a dentry object for every component of a pathname that a process looks up; the dentry object associates the component to its corresponding inode. For example, when looking up the /tmp/test pathname, the kernel creates a dentry object for the / root directory, a second dentry object for the tmp entry of the root directory, and a third dentry object for the test entry of the /tmp directory. Notice that dentry objects have no corresponding image on disk, and hence no field is included in the dentry structure to specify that the object has been modified. Dentry objects are stored in a slab allocator cache called dentry_cache; dentry objects are thus created and destroyed by invoking kmem_cache_alloc( ) and kmem_cache_free( ). Table 12-5. The fields of the dentry object Type Field Description atomic_t d_count Dentry object usage counter unsigned int d_flags Dentry flags struct inode * d_inode Inode associated with filename struct dentry * d_parent Dentry object of parent directory struct list_head d_hash Pointers for list in hash table entry struct list_head d_lru Pointers for unused list struct list_head d_child Pointers for the list of dentry objects included in parent directory struct list_head d_subdirs For directories, list of dentry objects of subdirectories struct list_head d_alias List of associated inodes (alias) int d_mounted Flag set to 1 if and only if the dentry is the mount point for a filesystem struct qstr d_name Filename unsigned long d_time Used by d_revalidate method struct dentry_operations* d_op Dentry methods struct super_block * d_sb Superblock object of the file unsigned long d_vfs_flags Dentry cache flags void * d_fsdata Filesystem-dependent data unsigned char * d_iname Space for short filename Each dentry object may be in one of four states: Free The dentry object contains no valid information and is not used by the VFS. The corresponding memory area is handled by the slab allocator. Unused The dentry object is not currently used by the kernel. The d_count usage counter of the object is 0, but the d_inode field still points to the associated inode. The dentry object contains valid information, but its contents may be discarded if necessary in order to reclaim memory. In use The dentry object is currently used by the kernel. The d_count usage counter is positive and the d_inode field points to the associated inode object. The dentry object contains valid information and cannot be discarded. Negative The inode associated with the dentry does not exist, either because the corresponding disk inode has been deleted or because the dentry object was created by resolving a pathname of a nonexisting file. The d_inode field of the dentry object is set to NULL, but the object still remains in the dentry cache so that further lookup operations to the same file pathname can be quickly resolved. The term "negative" is misleading since no negative value is involved. 12.2.5 The dentry Cache Since reading a directory entry from disk and constructing the corresponding dentry object requires considerable time, it makes sense to keep in memory dentry objects that you've finished with but might need later. For instance, people often edit a file and then compile it, or edit and print it, or copy it and then edit the copy. In such cases, the same file needs to be repeatedly accessed. To maximize efficiency in handling dentries, Linux uses a dentry cache, which consists of two kinds of data structures: ● A set of dentry objects in the in-use, unused, or negative state. ● A hash table to derive the dentry object associated with a given filename and a given directory quickly. As usual, if the required object is not included in the dentry cache, the hashing function returns a null value. The dentry cache also acts as a controller for an inode cache. The inodes in kernel memory that are associated with unused dentries are not discarded, since the dentry cache is still using them. Thus, the inode objects are kept in RAM and can be quickly referenced by means of the corresponding dentries. All the "unused" dentries are included in a doubly linked "Least Recently Used" list sorted by time of insertion. In other words, the dentry object that was last released is put in front of the list, so the least recently used dentry objects are always near the end of the list. When the dentry cache has to shrink, the kernel removes elements from the tail of this list so that the most recently used objects are preserved. The addresses of the first and last elements of the LRU list are stored in the next and prev fields of the dentry_unused variable. The d_lru field of the dentry object contains pointers to the adjacent dentries in the list. Each "in use" dentry object is inserted into a doubly linked list specified by the i_dentry field of the corresponding inode object (since each inode could be associated with several hard links, a list is required). The d_alias field of the dentry object stores the addresses of the adjacent elements in the list. Both fields are of type struct list_head. An "in use" dentry object may become "negative" when the last hard link to the corresponding file is deleted. In this case, the dentry object is moved into the LRU list of unused dentries. Each time the kernel shrinks the dentry cache, negative dentries move toward the tail of the LRU list so that they are gradually freed (see Section 16.7.6). The hash table is implemented by means of a dentry_hashtable array. Each element is a pointer to a list of dentries that hash to the same hash table value. The array's size depends on the amount of RAM installed in the system. The d_hash field of the dentry object contains pointers to the adjacent elements in the list associated with a single hash value. The hash function produces its value from both the address of the dentry object of the directory and the filename. The dcache_lock spin lock protects the dentry cache data structures against concurrent accesses in multiprocessor systems. The d_lookup( ) function looks in the hash table for a given parent dentry object and filename. The methods associated with a dentry object are called dentry operations; they are described by the dentry_operations structure, whose address is stored in the d_op field. Although some filesystems define their own dentry methods, the fields are usually NULL and the VFS replaces them with default functions. Here are the methods, in the order they appear in the dentry_operations table: d_revalidate(dentry, flag) Determines whether the dentry object is still valid before using it for translating a file pathname. The default VFS function does nothing, although network filesystems may specify their own functions. d_hash(dentry, name) Creates a hash value; this function is a filesystem-specific hash function for the dentry hash table. The dentry parameter identifies the directory containing the component. The name parameter points to a structure containing both the pathname component to be looked up and the value produced by the hash function. d_compare(dir, name1, name2) Compares two filenames; name1 should belong to the directory referenced by dir. The default VFS function is a normal string match. However, each filesystem can implement this method in its own way. For instance, MS-DOS does not distinguish capital from lowercase letters. d_delete(dentry) Called when the last reference to a dentry object is deleted (d_count becomes 0). The default VFS function does nothing. d_release(dentry) Called when a dentry object is going to be freed (released to the slab allocator). The default VFS function does nothing. d_iput(dentry, ino) Called when a dentry object becomes "negative"—that is, it loses its inode. The default VFS function invokes iput( ) to release the inode object. 12.2.6 Files Associated with a Process We mentioned in Section 1.5 that each process has its own current working directory and its own root directory. These are just two examples of data that must be maintained by the kernel to represent the interactions between a process and a filesystem. A whole data structure of type fs_struct is used for that purpose (see Table 12-6) and each process descriptor has an fs field that points to the process fs_struct structure. Table 12-6. The fields of the fs_struct structure Type Field Description atomic_t count Number of processes sharing this table rwlock_t lock Read/write spin lock for the table fields int umask Bit mask used when opening the file to set the file permissions struct dentry * root Dentry of the root directory struct dentry * pwd Dentry of the current working directory struct dentry * altroot Dentry of the emulated root directory (always NULL for the 80 x 86 architecture) struct vfsmount * rootmnt Mounted filesystem object of the root directory struct vfsmount * pwdmnt Mounted filesystem object of the current working directory struct vfsmount * altrootmnt Mounted filesystem object of the emulated root directory (always NULL for the 80 x 86 architecture) A second table, whose address is contained in the files field of the process descriptor, specifies which files are currently opened by the process. It is a files_struct structure whose fields are illustrated in Table 12-7. Table 12-7. The fields of the files_struct structure Type Field Description atomic_t count Number of processes sharing this table rwlock_t file_lock Read/write spin lock for the table fields int max_fds Current maximum number of file objects int max_fdset Current maximum number of file descriptors int next_fd Maximum file descriptors ever allocated plus 1 struct file ** fd Pointer to array of file object pointers fd_set * close_on_exec Pointer to file descriptors to be closed on exec( ) fd_set * open_fds Pointer to open file descriptors fd_set close_on_exec_init Initial set of file descriptors to be closed on exec( ) fd_set open_fds_init Initial set of file descriptors struct file ** fd_array Initial array of file object pointers The fd field points to an array of pointers to file objects. The size of the array is stored in the max_fds field. Usually, fd points to the fd_array field of the files_struct structure, which includes 32 file object pointers. If the process opens more than 32 files, the kernel allocates a new, larger array of file pointers and stores its address in the fd fields; it also updates the max_fds field. For every file with an entry in the fd array, the array index is the file descriptor. Usually, the first element (index 0) of the array is associated with the standard input of the process, the second with the standard output, and the third with the standard error (see Figure 12-3). Unix processes use the file descriptor as the main file identifier. Notice that, thanks to the dup( ), dup2( ), and fcntl( ) system calls, two file descriptors may refer to the same opened file—that is, two elements of the array could point to the same file object. Users see this all the time when they use shell constructs like 2>&1 to redirect the standard error to the standard output. A process cannot use more than NR_OPEN (usually, 1, 048 ,576) file descriptors. The kernel also enforces a dynamic bound on the maximum number of file descriptors in the rlim[RLIMIT_NOFILE] structure of the process descriptor; this value is usually 1,024, but it can be raised if the process has root privileges. The open_fds field initially contains the address of the open_fds_init field, which is a bitmap that identifies the file descriptors of currently opened files. The max_fdset field stores the number of bits in the bitmap. Since the fd_set data structure includes 1,024 bits, there is usually no need to expand the size of the bitmap. However, the kernel may dynamically expand the size of the bitmap if this turns out to be necessary, much as in the case of the array of file objects. Figure 12-3. The fd array The kernel provides an fget( ) function to be invoked when the kernel starts using a file object. This function receives as its parameter a file descriptor fd . It returns the address in current->files->fd[fd] (that is, the address of the corresponding file object), or NULL if no file corresponds to fd . In the first case, fget( ) increments the file object usage counter f_count by 1. The kernel also provides an fput( ) function to be invoked when a kernel control path finishes using a file object. This function receives as its parameter the address of a file object and decrements its usage counter, f_count. Moreover, if this field becomes 0, the function invokes the release method of the file operations (if defined), releases the associated dentry object and filesystem descriptor, decrements the i_writecount field in the inode object (if the file was opened for writing), and finally moves the file object from the "in use" list to the "unused" one. I l@ve RuBoard I l@ve RuBoard 12.3 Filesystem Types The Linux kernel supports many different types of filesystems. In the following, we introduce a few special types of filesystems that play an important role in the internal design of the Linux kernel. Next, we shall discuss filesystem registration—that is, the basic operation that must be performed, usually during system initialization, before using a filesystem type. Once a filesystem is registered, its specific functions are available to the kernel, so that type of filesystem can be mounted on the system's directory tree. 12.3.1 Special Filesystems While network and disk-based filesystems enable the user to handle information stored outside the kernel, special filesystems may provide an easy way for system programs and administrators to manipulate the data structures of the kernel and to implement special features of the operating system. Table 12-8 lists the most common special filesystems used in Linux; for each of them, the table reports its mount point and a short description. Notice that a few filesystems have no fixed mount point (keyword "any" in the table). These filesystems can be freely mounted and used by the users. Moreover, some other special filesystems do not have a mount point at all (keyword "none" in the table). They are not for user interaction, but the kernel can use them to easily reuse some of the VFS layer code; for instance, we'll see in Chapter 19 that, thanks to the pipefs special filesystem, pipes can be treated in the same way as FIFO files. Table 12-8. Most common special filesystems Name Mount point Description bdev none Block devices (see Chapter 13) binfmt_misc any Miscellaneous executable formats (see Chapter 20) devfs /dev Virtual device files (see Chapter 13) devpts /dev/pts Pseudoterminal support (Open Group's Unix98 standard) pipefs none Pipes (see Chapter 19) proc /proc General access point to kernel data structures rootfs none Provides an empty root directory for the bootstrap phase shm none IPC-shared memory regions (see Chapter 19) sockfs none Sockets (see Chapter 18) tmpfs any Temporary files (kept in RAM unless swapped) Special filesystems are not bound to physical block devices. However, the kernel assigns to each mounted special filesystem a fictitious block device that has the value 0 as major number and an arbitrary value (different for each special filesystem) as a minor number. The get_unnamed_dev( ) function returns a new fictitious block device identifier, while the put_unnamed_dev( ) function releases it. The unnamed_dev_in_use array contains a mask of 256 bits that record what minor numbers are currently in use. Although some kernel designers dislike the fictitious block device identifiers, they help the kernel to handle special filesystems and regular ones in a uniform way. We see a practical example of how the kernel defines and initializes a special filesystem in the later section Section 12.4.1. 12.3.2 Filesystem Type Registration Often, the user configures Linux to recognize all the filesystems needed when compiling the kernel for her system. But the code for a filesystem actually may either be included in the kernel image or dynamically loaded as a module (see Appendix B). The VFS must keep track of all filesystem types whose code is currently included in the kernel. It does this by performing filesystem type registration. Each registered filesystem is represented as a file_system_type object whose fields are illustrated in Table 12-9. Table 12-9. The fields of the file_system_type object Type Field Description const char * name Filesystem name int fs_flags Filesystem type flags struct super_block *(*)( ) read_super Method for reading superblock struct module * owner Pointer to the module implementing the filesystem (see Appendix B) struct file_system_type * next Pointer to the next list element struct list_head fs_supers Head of a list of superblock objects All filesystem-type objects are inserted into a simply linked list. The file_systems variable points to the first item, while the next field of the structure points to the next item in the list. The file_systems_lock read/write spin lock protects the whole list against concurrent accesses. The fs_supers field represents the head (first dummy element) of a list of superblock objects corresponding to mounted filesystems of the given type. The backward and forward links of a list element are stored in the s_instances field of the superblock object. The read_super field points to the filesystem-type-dependant function that reads the superblock from the disk device and copies it into the corresponding superblock object. The fs_flags field stores several flags, which are listed in Table 12-10. Table 12-10. The filesystem type flags Name Description FS_REQUIRES_DEV Any filesystem of this type must be located on a physical disk device. FS_NO_DCACHE No longer used. FS_NO_PRELIM No longer used. FS_SINGLE There can be only one superblock object for this filesystem type. FS_NOMOUNT Filesystem has no mount point (see Section 12.3.1). FS_LITTER Purge dentry cache after unmounting (for special filesystems). FS_ODD_RENAME "Rename" operations are "move" operations (for network filesystems). During system initialization, the register_filesystem( ) function is invoked for every filesystem specified at compile time; the function inserts the corresponding file_system_type object into the filesystem-type list. The register_filesystem( ) function is also invoked when a module implementing a filesystem is loaded. In this case, the filesystem may also be unregistered (by invoking the unregister_filesystem( ) function) when the module is unloaded. The get_fs_type( ) function, which receives a filesystem name as its parameter, scans the list of registered filesystems looking at the name field of their descriptors, and returns a pointer to the corresponding file_system_type object, if it is present. I l@ve RuBoard I l@ve RuBoard 12.4 Filesystem Mounting Each filesystem has its own root directory. The filesystem whose root directory is the root of the system's directory tree is called root filesystem. Other filesystems can be mounted on the system's directory tree; the directories on which they are inserted are called mount points. A mounted filesystem is the child of the mounted filesystem to which the mount point directory belongs. For instance, the /proc virtual filesystem is a child of the root filesystem (and the root filesystem is the parent of /proc). In most traditional Unix-like kernels, each filesystem can be mounted only once. Suppose that an Ext2 filesystem stored in the /dev/fd0 floppy disk is mounted on /flp by issuing the command: mount -t ext2 /dev/fd0 /flp Until the filesystem is unmounted by issuing a umount command, any other mount command acting on /dev/fd0 fails. However, Linux 2.4 is different: it is possible to mount the same filesystem several times. For instance, issuing the following command right after the previous one will likely succeed in Linux: mount -t ext2 -o ro /dev/fd0 /flp-ro As a result, the Ext2 filesystem stored in the floppy disk is mounted both on /flp and on /flp- ro; therefore, its files can be accessed through both /flp and /flp-ro (in this example, accesses through /flp-ro are read-only). Of course, if a filesystem is mounted n times, its root directory can be accessed through n mount points, one per mount operation. Although the same filesystem can be accessed by several paths, it is really unique. Thus, there is just one superblock object for all of them, no matter of how many times it has been mounted. Mounted filesystems form a hierarchy: the mount point of a filesystem might be a directory of a second filesystem, which in turn is already mounted over a third filesystem, and so on.[6] [6] Quite surprisingly, the mount point of a filesystem might be a directory of the same filesystem, provided that it was already mounted before. For instance: mount -t ext2 /dev/fd0 /flp; touch /flp/foo mkdir /flp/mnt; mount -t ext2 /dev/fd0 /flp/mnt Now, the empty foo file on the floppy filesystem can be accessed both as flp.foo and flp/mnt/foo. It is also possible to stack multiple mounts on a single mount point. Each new mount on the same mount point hides the previously mounted filesystem, although processes already using the files and directories under the old mount can continue to do so. When the topmost mounting is removed, then the next lower mount is once more made visible. As you can imagine, keeping track of mounted filesystems can quickly become a nightmare. For each mount operation, the kernel must save in memory the mount point and the mount flags, as well as the relationships between the filesystem to be mounted and the other mounted filesystems. Such information is stored in data structures named mounted filesystem descriptors; each descriptor is a data structure that has type vfsmount, whose fields are shown in Table 12-11. Table 12-11. The fields of the vfsmount data structure Type Field Description struct list_head mnt_hash Pointers for the hash table list struct vfsmount * mnt_parent Points to the parent filesystem on which this filesystem is mounted on struct dentry * mnt_mountpoint Points to the dentry of the mount directory of this filesystem struct dentry * mnt_root Points to the dentry of the root directory of this filesystem struct super_block * mnt_sb Points to the superblock object of this filesystem struct list_head mnt_mounts Head of the parent list of descriptors (relative to this filesystem) struct list_head mnt_child Pointers for the parent list of descriptors (relative to the parent filesystem) atomic_t mnt_count Usage counter int mnt_flags Flags char * mnt_devname Device file name struct list_head mnt_list Pointers for global list of descriptors The vfsmount data structures are kept in several doubly linked circular lists: ● A circular doubly linked "global" list including the descriptors of all mounted filesystems. The head of the list is a first dummy element, which is represented by the vfsmntlist variable. The mnt_list field of the descriptor contains the pointers to adjacent elements in the list. ● An hash table indexed by the address of the vfsmount descriptor of the parent filesystem and the address of the dentry object of the mount point directory. The hash table is stored in the mount_hashtable array, whose size depends on the amount of RAM in the system. Each item of the table is the head of a circular doubly linked list storing all descriptors that have the same hash value. The mnt_hash field of the descriptor contains the pointers to adjacent elements in this list. ● For each mounted filesystem, a circular doubly linked list including all child mounted filesystems. The head of each list is stored in the mnt_mounts field of the mounted filesystem descriptor; moreover, the mnt_child field of the descriptor stores the pointers to the adjacent elements in the list. The mount_sem semaphore protects the lists of mounted filesystem objects from concurrent accesses. The mnt_flags field of the descriptor stores the value of several flags that specify how some kinds of files in the mounted filesystem are handled. The flags are listed in Table 12- 12. Table 12-12. Mounted filesystem flags Name Description MNT_NOSUID Forbid setuid and setgid flags in the mounted filesystem MNT_NODEV Forbid access to device files in the mounted filesystem MNT_NOEXEC Disallow program execution in the mounted filesystem The following functions handle the mounted filesystem descriptors: alloc_vfsmnt( ) Allocates and initializes a mounted filesystem descriptor free_vfsmnt(mnt) Frees a mounted filesystem descriptor pointed by mnt lookup_mnt( parent,mountpoint) Looks up a descriptor in the hash table and returns its address 12.4.1 Mounting the Root Filesystem Mounting the root filesystem is a crucial part of system initialization. It is a fairly complex procedure because the Linux kernel allows the root filesystem to be stored in many different places, such as a hard disk partition, a floppy disk, a remote filesystem shared via NFS, or even a fictitious block device kept in RAM. To keep the description simple, let's assume that the root filesystem is stored in a partition of a hard disk (the most common case, after all). While the system boots, the kernel finds the major number of the disk that contains the root filesystem in the ROOT_DEV variable. The root filesystem can be specified as a device file in the /dev directory either when compiling the kernel or by passing a suitable "root" option to the initial bootstrap loader. Similarly, the mount flags of the root filesystem are stored in the root_mountflags variable. The user specifies these flags either by using the rdev external program on a compiled kernel image or by passing a suitable rootflags option to the initial bootstrap loader (see Appendix A). Mounting the root filesystem is a two-stage procedure, shown in the following list. 1. The kernel mounts the special rootfs filesystem, which just provides an empty directory that serves as initial mount point. 2. The kernel mounts the real root filesystem over the empty directory. Why does the kernel bother to mount the rootfs filesystem before the real one? Well, the rootfs filesystem allows the kernel to easily change the real root filesystem. In fact, in some cases, the kernel mounts and unmounts several root filesystems, one after the other. For instance, the initial bootstrap floppy disk of a distribution might load in RAM a kernel with a minimal set of drivers, which mounts as root a minimal filesystem stored in a RAM disk. Next, the programs in this initial root filesystem probe the hardware of the system (for instance, they determine whether the hard disk is EIDE, SCSI, or whatever), load all needed kernel modules, and remount the root filesystem from a physical block device. The first stage is performed by the init_mount_tree( ) function, which is executed during system initialization: struct file_system_type root_fs_type; root_fs_type.name = "rootfs"; root_fs_type.read_super = rootfs_read_super; root_fs_type.fs_flags = FS_NOMOUNT; register_filesystem(&root_fs_type); root_vfsmnt = do_kern_mount("rootfs", 0, "rootfs", NULL); The root_fs_type variable stores the descriptor object of the rootfs special filesystem; its fields are initialized, and then it is passed to the register_filesystem( ) function (see the earlier section Section 12.3.2). The do_kern_mount( ) function mounts the special filesystem and returns the address of a new mounted filesystem object; this address is saved by init_mount_tree( ) in the root_vfsmnt variable. From now on, root_vfsmnt represents the root of the tree of the mounted filesystems. The do_kern_mount( ) function receives the following parameters: type The type of filesystem to be mounted flags The mount flags (see Table 12-13 in the later section Section 12.4.2) name The device file name of the block device storing the filesystem (or the filesystem type name for special filesystems) data Pointers to additional data to be passed to the read_super method of the filesystem The function takes care of the actual mount operation by performing the following operations: 1. Checks whether the current process has the privileges for the mount operation (the check always succeeds when the function is invoked by init_mount_tree( ) because the system initialization is carried on by a process owned by root). 2. Invokes get_fs_type( ) to search in the list of filesystem types and locate the name stored in the type parameter; get_fs_type( ) returns the address of the corresponding file_system_type descriptor. 3. Invokes alloc_vfsmnt( ) to allocate a new mounted filesystem descriptor and stores its address in the mnt local variable. 4. Initializes the mnt->mnt_devname field with the content of the name parameter. 5. Allocates a new superblock and initializes it. do_kern_mount( ) checks the flags in the file_system_type descriptor to determine how to do this: a. If FS_REQUIRES_DEV is on, invokes get_sb_bdev( ) (see the later section Section 12.4.2) b. If FS_SINGLE is on, invokes get_sb_single( ) (see the later section Section 12.4.2) c. Otherwise, invokes get_sb_nodev( ) 6. If the FS_NOMOUNT flag in the file_system_type descriptor is on, sets the MS_NOUSER flag in the superblock object. 7. Initializes the mnt->mnt_sb field with the address of the new superblock object. 8. Initializes the mnt->mnt_root and mnt->mnt_mountpoint fields with the address of the dentry object corresponding to the root directory of the filesystem. 9. Initializes the mnt->mnt_parent field with the value in mnt (the newly mounted filesystem has no parent). 10. Releases the s_umount semaphore of the superblock object (it was acquired when the object was allocated in Step 5). 11. Returns the address mnt of the mounted filesystem object. When the do_kern_mount( ) function is invoked by init_mount_tree( ) to mount the rootfs special filesystem, neither the FS_REQUIRES_DEV flag nor the FS_SINGLE flag are set, so the function uses get_sb_nodev( ) to allocate the superblock object. This function executes the following steps: 1. Invokes get_unnamed_dev( ) to allocate a new fictitious block device identifier (see the earlier section Section 12.3.1). 2. Invokes the read_super( ) function, passing to it the filesystem type object, the mount flags, and the fictitious block device identifier. In turn, this function performs the following actions: a. Allocates a new superblock object and puts its address in the local variable s. b. Initializes the s->s_dev field with the block device identifier. c. Initializes the s->s_flags field with the mount flags (see Table 12-13). d. Initializes the s->s_type field with the filesystem type descriptor of the filesystem. e. Acquires the sb_lock spin lock. f. Inserts the superblock in the global circular list whose head is super_blocks. g. Inserts the superblock in the filesystem type list whose head is s->s_type- >fs_supers. h. Releases the sb_lock spin lock. i. Acquires for writing the s->s_umount read/write semaphore. j. Acquires the s->s_lock semaphore. k. Invokes the read_super method of the filesystem type. l. Sets the MS_ACTIVE flag in s->s_flags. m. Releases the s->s_lock semaphore. n. Returns the address s of the superblock. 3. If the filesystem type is implemented by a kernel module, increments its usage counter. 4. Returns the address of the new superblock. The second stage of the mount operation for the root filesystem is performed by the mount_root( ) function near the end of the system initialization. For the sake of brevity, we consider the case of a disk-based filesystem whose device files are handled in the traditional way (we briefly discuss in Chapter 13 how the devfs virtual filesystem offers an alternative way to handle device files). In this case, the function performs the following operations: 1. Allocates a buffer and fills it with a list of filesystem type names. This list is either passed to the kernel in the rootfstype boot parameter or is built by scanning the elements in the simply linked list of filesystem types. 2. Invokes the bdget( ) and blkdev_get( ) functions to check whether the ROOT_DEV root device exists and is properly working. 3. Invokes get_super( ) to search for a superblock object associated with the ROOT_DEV device in the super_blocks list. Usually none is found because the root filesystem is still to be mounted. The check is made, however, because it is possible to remount a previously mounted filesystem. Usually the root filesystem is mounted twice during the system boot: the first time as a read-only filesystem so that its integrity can be safely checked; the second time for reading and writing so that normal operations can start. We'll suppose that no superblock object associated with the ROOT_DEV device is found in the super_blocks list. 4. Scans the list of filesystem type names built in Step 1. For each name, invokes get_fs_type( ) to get the corresponding file_system_type object, and invokes read_super( ) to attempt to read the corresponding superblock from disk. As described earlier, this function allocates a new superblock object and attempts to fill it by using the method to which the read_super field of the file_system_type object points. Since each filesystem-specific method uses unique magic numbers, all read_super( ) invocations will fail except the one that attempts to fill the superblock by using the method of the filesystem really used on the root device. The read_super( ) method also creates an inode object and a dentry object for the root directory; the dentry object maps to the inode object. 5. Allocates a new mounted filesystem object and initializes its fields with the ROOT_DEV block device name, the address of the superblock object, and the address of the dentry object of the root directory. 6. Invokes the graft_tree( ) function, which inserts the new mounted filesystem object in the children list of root_vfsmnt, in the global list of mounted filesystem objects, and in the mount_hashtable hash table. 7. Sets the root and pwd fields of the fs_struct table of current (the init process) to the dentry object of the root directory. 12.4.2 Mounting a Generic Filesystem Once the root filesystem is initialized, additional filesystems may be mounted. Each must have its own mount point, which is just an already existing directory in the system's directory tree. The mount( ) system call is used to mount a filesystem; its sys_mount( ) service routine acts on the following parameters: ● The pathname of a device file containing the filesystem, or NULL if it is not required (for instance, when the filesystem to be mounted is network-based) ● The pathname of the directory on which the filesystem will be mounted (the mount point) ● The filesystem type, which must be the name of a registered filesystem ● The mount flags (permitted values are listed in Table 12-13) ● A pointer to a filesystem-dependent data structure (which may be NULL) Table 12-13. Mount flags Macro Description MS_RDONLY Files can only be read MS_NOSUID Forbid setuid and setgid flags MS_NODEV Forbid access to device files MS_NOEXEC Disallow program execution MS_SYNCHRONOUS Write operations are immediate MS_REMOUNT Remount the filesystem changing the mount flags MS_MANDLOCK Mandatory locking allowed MS_NOATIME Do not update file access time MS_NODIRATIME Do not update directory access time MS_BIND Create a "bind mount," which allows making a file or directory visible at another point of the system directory tree MS_MOVE Atomically move a mounted filesystem on another mount point MS_REC Should recursively create "bind mounts" for a directory subtree (still unfinished in 2.4.18) MS_VERBOSE Generate kernel messages on mount errors The sys_mount( ) function copies the value of the parameters into temporary kernel buffers, acquires the big kernel lock, and invokes the do_mount( ) function. Once do_mount( ) returns, the service routine releases the big kernel lock and frees the temporary kernel buffers. The do_mount( ) function takes care of the actual mount operation by performing the following operations: 1. Checks whether the sixteen highest-order bits of the mount flags are set to the "magic" value 0xce0d; in this case, they are cleared. This is a legacy hack that allows the sys_mount( ) service routine to be used with old C libraries that do not handle the highest-order flags. 2. If any of the MS_NOSUID, MS_NODEV, or MS_NOEXEC flags passed as a parameter are set, clears them and sets the corresponding flag (MNT_NOSUID, MNT_NODEV, MNT_NOEXEC) in the mounted filesystem object. 3. Looks up the pathname of the mount point by invoking path_init( ) and path_walk( ) (see the later section Section 12.5). 4. Examines the mount flags to determine what has to be done. In particular: a. If the MS_REMOUNT flag is specified, the purpose is usually to change the mount flags in the s_flags field of the superblock object and the mounted filesystem flags in the mnt_flags field of the mounted filesystem object. The do_remount( ) function performs these changes. b. Otherwise, checks the MS_BIND flag. If it is specified, the user is asking to make visible a file or directory on another point of the system directory tree. Usually, this is done when mounting a filesystem stored in a regular file instead of a physical disk partition (loopback). The do_loopback( ) function accomplishes this task. c. Otherwise, checks the MS_MOVE flag. If it is specified, the user is asking to change the mount point of an already mounted filesystem. The do_move_mount( ) function does this atomically. d. Otherwise, invokes do_add_mount( ). This is the most common case. It is triggered when the user asks to mount either a special filesystem or a regular filesystem stored in a disk partition. do_add_mount( ) performs the following actions: a. Invokes do_kern_mount( ) passing, to it the filesystem type, the mount flags, and the block device name. As already described in Section 12.4.1, do_kern_mount( ) takes care of the actual mount operation. b. Acquires the mount_sem semaphore. c. Initializes the flags in the mnt_flags field of the new mounted filesystem object allocated by do_kern_mount( ). d. Invokes graft_tree( ) to insert the new mounted filesystem object in the global list, in the hash table, and in the children list of the parent-mounted filesystem. e. Releases the mount_sem semaphore. 5. Invokes path_release( ) to terminate the pathname lookup of the mount point (see the later section Section 12.5). The core of the mount operation is the do_kern_mount( ) function, which we already described in the earlier section Section 12.4.1. Recall that this function checks the filesystem type flags to determine how the mount operation is to be done. For a regular disk-based filesystem, the FS_REQUIRES_DEV flag is set, so do_kern_mount( ) invokes the get_sb_bdev( ) function, which performs the following actions: 1. Invokes path_init( ) and path_walk( ) to look up the pathname of the mount point (see Section 12.5). 2. Invokes blkdev_get( ) to open the block device storing the regular filesystem. 3. Searches the list of superblock objects; if a superblock relative to the block device is already present, returns its address. This means that the filesystem is already mounted and will be mounted again. 4. Otherwise, allocates a new superblock object, initializes its s_dev, s_bdev, s_flags, and s_type fields, and inserts it into the global lists of superblocks and the superblock list of the filesystem type descriptor. 5. Acquires the s_lock spin lock of the superblock. 6. Invokes the read_super method of the filesystem type to access the superblock information on disk and fill the other fields of the new superblock object. 7. Sets the MS_ACTIVE flag of the superblock. 8. Releases the s_lock spin lock of the superblock. 9. If the filesystem type is implemented by a kernel module, increments its usage counter. 10. Invokes path_release( ) to terminate the mount point lookup operation. 11. Returns the address of the new superblock object. 12.4.3 Unmounting a Filesystem The umount( ) system call is used to unmount a filesystem. The corresponding sys_umount( ) service routine acts on two parameters: a filename (either a mount point directory or a block device filename) and a set of flags. It performs the following actions: 1. Invokes path_init( ) and path_walk( ) to look up the mount point pathname (see the next section). Once finished, the functions return the address d of the dentry object corresponding to the pathname. 2. If the resulting directory is not the mount point of a filesystem, returns the -EINVAL error code. This check is done by verifying that d->mnt->mnt_root contains the address of the dentry object d. 3. If the filesystem to be unmounted has not been mounted on the system directory tree, returns the -EINVAL error code. (Recall that some special filesystems have no mount point.) This check is done by invoking the check_mnt( ) function on d- >mnt. 4. If the user does not have the privileges required to unmount the filesystem, returns the -EPERM error code. 5. Invokes do_umount( ), which performs the following operations: a. Retrieves the address of the superblock object from the mnt_sb field of the mounted filesystem object. b. If the user asked to force the unmount operation, interrupts any ongoing mount operation by invoking the umount_begin superblock operation. c. If the filesystem to be unmounted is the root filesystem and the user didn't ask to actually detach it, invokes do_remount_sb( ) to remount the root filesystem read-only and terminates. d. Acquires the mount_sem semaphore for writing and the dcache_lock dentry spin lock. e. If the mounted filesystem does not include mount points for any child mounted filesystem, or if the user asked to forcibly detach the filesystem, invokes umount_tree( ) to unmount the filesystem (together with all children). f. Releases mount_sem and dcache_lock. I l@ve RuBoard I l@ve RuBoard 12.5 Pathname Lookup In this section, we illustrate how the VFS derives an inode from the corresponding file pathname. When a process must identify a file, it passes its file pathname to some VFS system call, such as open( ), mkdir( ), rename( ), or stat( ). The standard procedure for performing this task consists of analyzing the pathname and breaking it into a sequence of filenames. All filenames except the last must identify directories. If the first character of the pathname is / , the pathname is absolute, and the search starts from the directory identified by current->fs->root (the process root directory). Otherwise, the pathname is relative and the search starts from the directory identified by current->fs->pwd (the process-current directory). Having in hand the inode of the initial directory, the code examines the entry matching the first name to derive the corresponding inode. Then the directory file that has that inode is read from disk and the entry matching the second name is examined to derive the corresponding inode. This procedure is repeated for each name included in the path. The dentry cache considerably speeds up the procedure, since it keeps the most recently used dentry objects in memory. As we saw before, each such object associates a filename in a specific directory to its corresponding inode. In many cases, therefore, the analysis of the pathname can avoid reading the intermediate directories from the disk. However, things are not as simple as they look, since the following Unix and VFS filesystem features must be taken into consideration: ● The access rights of each directory must be checked to verify whether the process is allowed to read the directory's content. ● A filename can be a symbolic link that corresponds to an arbitrary pathname; in this case, the analysis must be extended to all components of that pathname. ● Symbolic links may induce circular references; the kernel must take this possibility into account and break endless loops when they occur. ● A filename can be the mount point of a mounted filesystem. This situation must be detected, and the lookup operation must continue into the new filesystem. Pathname lookup is performed by three functions: path_init( ), path_walk( ), and path_release( ). They are always invoked in this exact order. The path_init( ) function receives three parameters: name A pointer to the file pathname to be resolved. flags The value of flags that represent how the looked-up file is going to be accessed. The flags are listed in Table 12-17 in the later section Section 12.6.1.[7] [7] There is, however, a small difference in how the O_RDONLY, O_WRONLY, and O_RDWR flags are encoded. The bit at index 0 (lowest-order) of the flags parameter is set only if the file access requires read privileges; similarly, the bit at index 1 is set only if the file access requires write privileges. Conversely, for the open( ) system call, the value of the O_WRONLY flag is stored in the bit at index 0, while the O_RDWR flag is stored in the bit at index 1; thus, the O_RDONLY flag is true when both bits are cleared. Notice that it is not possible to specify in the open( ) system call that a file access does not require either read or write privileges; this makes sense, however, in a pathname lookup operation involving symbolic links. nd The address of a struct nameidata data structure. The struct nameidata data structure is filled by path_walk( ) with data pertaining to the pathname lookup operation. The fields of this structure are shown in Table 12-14. Table 12-14. The fields of the nameidata data structure Type Field Description struct dentry * dentry Address of the dentry object struct vfs_mount * mnt Address of the mounted filesystem object struct qstr last Last component of the pathname (used when the LOOKUP_PARENT flag is set) unsigned int flags Lookup flags int last_type Type of last component of the pathname (used when the LOOKUP_PARENT flag is set) The dentry and mnt fields point respectively to the dentry object and the mounted filesystem object of the last resolved component in the pathname. Once path_walk( ) successfully returns, these two fields "describe" the file that is identified by the given pathname. The flags field stores the value of some flags used in the lookup operation; they are listed in Table 12-15. Table 12-15. The flags of the lookup operation Macro Description LOOKUP_FOLLOW If the last component is a symbolic link, interpret (follow) it. LOOKUP_DIRECTORY The last component must be a directory. LOOKUP_CONTINUE There are still filenames to be examined in the pathname (used only by NFS). LOOKUP_POSITIVE The pathname must identify an existing file. LOOKUP_PARENT Look up the directory including the last component of the pathname. LOOKUP_NOALT Do not consider the emulated root directory (always set for the 80 x 86 architecture). The goal of the path_init( ) function consists of initializing the nameidata structure, which it does in the following manner: 1. Sets the dentry field with the address of the dentry object of the directory where the pathname lookup operation starts. If the pathname is relative (it doesn't start with a slash), the field points to the dentry of the working directory (current->fs- >pwd); otherwise it points to the dentry of the root directory of the process (current->fs->root). 2. Sets the mnt field with the address of the mounted filesystem object relative to the directory where the pathname lookup operation starts: either current->fs- >pwdmnt or current->fs->rootmnt, according to whether the pathname is relative or absolute. 3. Initializes the flags field with the value of the flags parameter. 4. Initializes the last_type field to LAST_ROOT. Once path_init( ) initializes the nameidata data structure, the path_walk( ) function takes care of the lookup operation, and stores in the nameidata structure the pointers to the dentry object and mounted filesystem object relative to the last component of the pathname. The function also increments the usage counters of the objects referenced by nd- >dentry and nd->mnt so that the caller function may safely access them once path_walk( ) returns. When the caller finishes accessing them, it invokes the third function of the set, path_release( ), which receives as a parameter the address of the nameidata data structure and decrements the two usage counters of nd->dentry and nd- >mnt. We are now ready to describe the core of the pathname lookup operation, namely the path_walk( ) function. It receives as parameters a pointer name to the pathname to be resolved and the address nd of the nameidata data structure. The function initializes to zero the total_link_count of the current process (see the later section Section 12.5.3), and then invokes link_path_walk( ). This latter function acts on the same two parameters of path_walk( ). To make things a bit easier, we first describe what link_path_walk( ) does when LOOKUP_PARENT is not set and the pathname does not contain symbolic links (standard pathname lookup). Next, we discuss the case in which LOOKUP_PARENT is set: this type of lookup is required when creating, deleting, or renaming a directory entry, that is, during a parent pathname lookup. Finally, we explain how the function resolves the symbolic links. 12.5.1 Standard Pathname Lookup When the LOOKUP_PARENT flag is cleared, link_path_walk( ) performs the following steps. 1. Initializes the lookup_flags local variable with nd->flags. 2. Skips any leading slash ( / ) before the first component of the pathname. 3. If the remaining pathname is empty, returns the value 0. In the nameidata data structure, the dentry and mnt fields point to the object relative to the last resolved component of the original pathname. 4. If the link_count field in the descriptor of the current process is positive, sets the LOOKUP_FOLLOW flag in the lookup_flags local variable (see Section 12.5.3). 5. Executes a cycle that breaks name into components (the intermediate slashes are treated as filename separators); for each component found, the function: a. Retrieves the address of the inode object of the last resolved component from nd->dentry->d_inode. b. Checks that the permissions of the last resolved component stored into the inode allow execution (in Unix, a directory can be traversed only if it is executable). If the inode has a custom permission method, the function executes it; otherwise, it executes the vfs_permission( ) function, which examines the access mode stored in the i_mode inode field and the privileges of the running process. c. Considers the next component to be resolved. From its name, it computes a hash value for the dentry cache hash table. d. Skips any trailing slash ( / ) after the slash that terminates the name of the component to be resolved. e. If the component to be resolved is the last one in the original pathname, jump to Step 6. f. If the name of the component is "." (a single dot), continues with the next component ("." refers to the current directory, so it has no effect inside a pathname). g. If the name of the component is ". ." (two dots), tries to climb to the parent directory: 1. If the last resolved directory is the process's root directory (nd- >dentry is equal to current->fs->root and nd->mnt is equal to current->fs->rootmnt), continues with the next component. 2. If the last resolved directory is the root directory of a mounted filesystem (nd->dentry is equal to nd->mnt->mnt_root), sets nd- >mnt to nd->mnt->mnt_parent and nd->dentry to nd->mnt- >mnt_mountpoint, and then restarts Step 5.g. (Recall that several filesystems can be mounted on the same mount point). 3. If the last resolved directory is not the root directory of a mounted filesystem, sets nd->dentry to nd->dentry->d_parent and continues with the next component. h. The component name is neither "." nor ". .", so the function must look it up in the dentry cache. If the low-level filesystem has a custom d_hash dentry method, the function invokes it to modify the hash value already computed in Step 5.c. i. Invokes cached_lookup( ), passing as parameters nd->dentry, the name of the component to be resolved, the hash value, and the LOOKUP_CONTINUE flag, which specifies that this is not the last component of the pathname. The function invokes d_lookup( ) to search the dentry object of the component in the dentry cache. If cached_lookup( ) fails in finding the dentry in the cache, link_walk_path( ) invokes real_lookup( ) to read the directory from disk and create a new dentry object. In either case, we can assume at the end of this step that the dentry local variable points to the dentry object of the component name to be resolved in this cycle. j. Checks whether the component just resolved (dentry local variable) refers to a directory that is a mount point for some filesystem (dentry- >d_mounted is set to 1). In this case, invokes lookup_mnt( ), passing to it dentry and nd->mnt, in order to get the address mounted of the child mounted filesystem object. Next, it sets dentry to mounted->mnt_root and nd->mnt to mounted. Then it repeats the whole step (several filesystems can be mounted on the same mount point). k. Checks whether the inode object dentry->d_inode has a custom follow_link method. If this is the case, the component is a symbolic link, which is described in the later section Section 12.5.3. l. Checks that dentry points to the dentry object of a directory (dentry- >d_inode->i_op->lookup method is defined). If not, returns the error - ENOTDIR, because the component is in the middle of the original pathname. m. Sets nd->dentry to dentry and continues with the next component of the pathname. 6. Now all components of the original pathname are resolved except the last one. If the pathname has a trailing slash, it sets the LOOKUP_FOLLOW and LOOKUP_DIRECTORY in the lookup_flags local variable to force interpretation of the last component as a directory name. 7. Checks the value of the LOOKUP_PARENT flag in the lookup_flags variable. In the following, we assume that the flag is set to 0, and we postpone the opposite case to the next section. 8. If the name of the last component is "." (a single dot), terminates the execution returning the value 0 (no error). In the nameidata structure that nd points to, the dentry and mnt fields refer to the objects relative to the next-to-last component of the pathname (any component "." has no effect inside a pathname). 9. If the name of the last component is ". ." (two dots), tries to climb to the parent directory: a. If the last resolved directory is the process's root directory (nd->dentry is equal to current->fs->root and nd->mnt is equal to current->fs- >rootmnt), terminates the execution returning the value 0 (no error). nd- >dentry and nd->mnt refer to the objects relative to the next to the last component of the pathname—that is, to the root directory of the process. b. If the last resolved directory is the root directory of a mounted filesystem (nd->dentry is equal to nd->mnt->mnt_root), sets nd->mnt to nd->mnt- >mnt_parent and nd->dentry to nd->mnt->mnt_mountpoint, and then restarts Step 5.j. c. If the last resolved directory is not the root directory of a mounted filesystem, sets nd->dentry to nd->dentry->d_parent, and terminates the execution returning the value 0 (no error). nd->dentry and nd->mnt refer to the objects relative to the next-to-last component of the pathname. 10. The name of the last component is neither "." nor ". .", so the function must look it up in the dentry cache. If the low-level filesystem has a custom d_hash dentry method, the function invokes it to modify the hash value already computed in Step 5.c. 11. Invokes cached_lookup( ), passing as parameters nd->dentry, the name of the component to be resolved, the hash value, and no flag (LOOKUP_CONTINUE is not set because this is the last component of the pathname). If cached_lookup( ) fails in finding the dentry in the cache, it also invokes real_lookup( ) to read the directory from disk and create a new dentry object. In either case, we can assume at the end of this step that the dentry local variable points to the dentry object of the component name to be resolved in this cycle. 12. Checks whether the component just resolved (dentry local variable) refers to a directory that is a mount point for some filesystem (dentry->d_mounted is set to 1). In this case, invokes lookup_mnt( ), passing to it dentry and nd->mnt, in order to get the address mounted of the child mounted filesystem object. Next, it sets dentry to mounted->mnt_root and nd->mnt to mounted. Then it repeats the whole step (because several filesystems can be mounted on the same mount point). 13. Checks whether LOOKUP_FOLLOW flag is set in lookup_flags and the inode object dentry->d_inode has a custom follow_link method. If this is the case, the component is a symbolic link that must be interpreted, as described in the later section Section 12.5.3. 14. Sets nd->dentry with the value stored in the dentry local variable. This dentry object is "the result" of the lookup operation. 15. Checks whether nd->dentry->d_inode is NULL. This happens when there is no inode associated with the dentry object, usually because the pathname refers to a nonexisting file. In this case: a. If either LOOKUP_POSITIVE or LOOKUP_DIRECTORY is set in lookup_flags, it terminates, returning the error code -ENOENT. b. Otherwise, it terminates returning the value 0 (no error). nd->dentry points to the negative dentry object created by the lookup operation. 16. There is an inode associated with the last component of the pathname. If the LOOKUP_DIRECTORY flag is set in lookup_flags, checks that the inode has a custom lookup method—that is, it is a directory. If not, terminates returning the error code -ENOTDIR. 17. Terminates returning the value 0 (no error). nd->dentry and nd->mnt refer to the last component of the pathname. 12.5.2 Parent Pathname Lookup In many cases, the real target of a lookup operation is not the last component of the pathname, but the next-to-last one. For example, when a file is created, the last component denotes the filename of the not yet existing file, and the rest of the pathname specifies the directory in which the new link must be inserted. Therefore, the lookup operation should fetch the dentry object of the next-to-last component. For another example, unlinking a file identified by the pathname /foo/bar consists of removing bar from the directory foo. Thus, the kernel is really interested in accessing the file directory foo rather than bar. The LOOKUP_PARENT flag is used whenever the lookup operation must resolve the directory containing the last component of the pathname, rather than the last component itself. When the LOOKUP_PARENT flag is set, the path_walk( ) function also sets up the last and last_type fields of the nameidata data structure. The last field stores the name of the last component in the pathname. The last_type field identifies the type of the last component; it may be set to one of the values shown in Table 12-16. Table 12-16. The values of the last_type field in the nameidata data structure Value Description LAST_NORM Last component is a regular filename LAST_ROOT Last component is "/ " (that is, the entire pathname is "/ ") LAST_DOT Last component is "." LAST_DOTDOT Last component is ". ." LAST_BIND Last component is a symbolic link into a special filesystem The LAST_ROOT flag is the default value set by path_init( ) when the whole pathname lookup operation starts (see the description at the beginning of Section 12.5). If the pathname turns out to be just "/ ", the kernel does not change the initial value of the last_type field. The LAST_BIND flag is set by the follow_link inode object's method of symbolic links in special filesystems (see the next section). The remaining values of the last_type field are set by link_path_walk( ) when the LOOKUP_PARENT flag is on; in this case, the function performs the same steps described in the previous section up to Step 7. From Step 7 onward, however, the lookup operation for the last component of the pathname is different: 1. Sets nd->last to the name of the last component 2. Initializes nd->last_type to LAST_NORM 3. If the name of the last component is "." (a single dot), sets nd->last_type to LAST_DOT 4. If the name of the last component is ". ." (two dots), sets nd->last_type to LAST_DOTDOT 5. Terminates by returning the value 0 (no error) As you can see, the last component is not interpreted at all. Thus, when the function terminates, the dentry and mnt fields of the nameidata data structure point to the objects relative to the directory that includes the last component. 12.5.3 Lookup of Symbolic Links Recall that a symbolic link is a regular file that stores a pathname of another file. A pathname may include symbolic links, and they must be resolved by the kernel. For example, if /foo/bar is a symbolic link pointing to (containing the pathname) ../dir, the pathname /foo/bar/file must be resolved by the kernel as a reference to the file /dir/file. In this example, the kernel must perform two different lookup operations. The first one resolves /foo/bar; when the kernel discovers that bar is the name of a symbolic link, it must retrieve its content and interpret it as another pathname. The second pathname operation starts from the directory reached by the first operation and continues until the last component of the symbolic link pathname has been resolved. Next, the original lookup operation resumes from the dentry reached in the second one and with the component following the symbolic link in the original pathname. To further complicate the scenario, the pathname included in a symbolic link may include other symbolic links. You might think that the kernel code that resolves the symbolic links is hard to understand, but this is not true; the code is actually quite simple because it is recursive. However, untamed recursion is intrinsically dangerous. For instance, suppose that a symbolic link points to itself. Of course, resolving a pathname including such a symbolic link may induce an endless stream of recursive invocations, which in turn quickly leads to a kernel stack overflow. The link_count field in the descriptor of the current process is used to avoid the problem: the field is incremented before each recursive execution and decremented right after. If the field reaches the value 5, the whole lookup operation terminates with an error code. Therefore, the level of nesting of symbolic links can be at most 5. Furthermore, the total_link_count field in the descriptor of the current process keeps track of how many symbolic links (even nonnested) were followed in the original lookup operation. If this counter reaches the value 40, the lookup operation aborts. Without this counter, a malicious user could create a pathological pathname including many consecutive symbolic links that freezes the kernel in a very long lookup operation. This is how the code basically works: once the link_path_walk( ) function retrieves the dentry object associated with a component of the pathname, it checks whether the corresponding inode object has a custom follow_link method (see Step 5.k and Step 13 in Section 12.5.1). If so, the inode is a symbolic link that must be interpreted before proceeding with the lookup operation of the original pathname. In this case, the link_path_walk( ) function invokes do_follow_link( ), passing to it the address of the dentry object of the symbolic link and the address of the nameidata data structure. In turn, do_follow_link( ) performs the following steps: 1. Checks that current->link_count is less than 5; otherwise, returns the error code -ELOOP 2. Checks that current->total_link_count is less than 40; otherwise, returns the error code -ELOOP 3. If the current->need_resched flag is set, invokes schedule( ) to give a chance to preempt the running process 4. Increments current->link_count and current->total_link_count 5. Updates the access time of the inode object associated with the symbolic link to be resolved 6. Invokes the follow_link method of the inode, passing to it the addresses of the dentry object and of the nameidata data structure 7. Decrements the current->link_count field 8. Returns the error code returned by the follow_link method (0 for no error) The follow_link method is a filesystem-dependent function that reads the pathname stored in the symbolic link from the disk. Having filled a buffer with the symbolic link's pathname, most follow_link methods end up invoking the vfs_follow_link( ) function and returning the value taken from it. In turn, the vfs_follow_link( ) does the following: 1. Checks whether the first character of the symbolic link pathname is a slash; if so, the dentry and mnt fields of the nameidata data structure are set so they refer to the current process root directory. 2. Invokes link_path_walk( ) to resolve the symbolic link pathname, passing to it the nameidata data structure. 3. Returns the value taken from link_path_walk( ). When do_follow_link( ) finally terminates, it returns the address of the dentry object referred to by the symbolic link to the original execution of link_path_walk( ). The link_path_walk( ) assigns this address to the dentry local variable, and then proceeds with the next step. I l@ve RuBoard I l@ve RuBoard 12.6 Implementations of VFS System Calls For the sake of brevity, we cannot discuss the implementation of all the VFS system calls listed in Table 12-1. However, it could be useful to sketch out the implementation of a few system calls, just to show how VFS's data structures interact. Let's reconsider the example proposed at the beginning of this chapter: a user issues a shell command that copies the MS-DOS file /floppy/TEST to the Ext2 file /tmp/test. The command shell invokes an external program like cp, which we assume executes the following code fragment: inf = open("/floppy/TEST", O_RDONLY, 0); outf = open("/tmp/test", O_WRONLY | O_CREAT | O_TRUNC, 0600); do { len = read(inf, buf, 4096); write(outf, buf, len); } while (len); close(outf); close(inf); Actually, the code of the real cp program is more complicated, since it must also check for possible error codes returned by each system call. In our example, we just focus our attention on the "normal" behavior of a copy operation. 12.6.1 The open( ) System Call The open( ) system call is serviced by the sys_open( ) function, which receives as parameters the pathname filename of the file to be opened, some access mode flags flags, and a permission bit mask mode if the file must be created. If the system call succeeds, it returns a file descriptor—that is, the index assigned to the new file in the current->files->fd array of pointers to file objects; otherwise, it returns -1. In our example, open( ) is invoked twice; the first time to open /floppy/TEST for reading (O_RDONLY flag) and the second time to open /tmp/test for writing (O_WRONLY flag). If /tmp/test does not already exist, it is created (O_CREAT flag) with exclusive read and write access for the owner (octal 0600 number in the third parameter). Conversely, if the file already exists, it is rewritten from scratch (O_TRUNC flag). Table 12-17 lists all flags of the open( ) system call. Table 12-17. The flags of the open( ) system call Flag name Description O_RDONLY Open for reading O_WRONLY Open for writing O_RDWR Open for both reading and writing O_CREAT Create the file if it does not exist O_EXCL With O_CREAT, fail if the file already exists O_NOCTTY Never consider the file as a controlling terminal O_TRUNC Truncate the file (remove all existing contents) O_APPEND Always write at end of the file O_NONBLOCK No system calls will block on the file O_NDELAY Same as O_NONBLOCK O_SYNC Synchronous write (block until physical write terminates) FASYNC Asynchronous I/O notification via signals O_DIRECT Direct I/O transfer (no kernel buffering) O_LARGEFILE Large file (size greater than 2 GB) O_DIRECTORY Fail if file is not a directory O_NOFOLLOW Do not follow a trailing symbolic link in pathname Let's describe the operation of the sys_open( ) function. It performs the following steps: 1. Invokes getname( ) to read the file pathname from the process address space. 2. Invokes get_unused_fd( ) to find an empty slot in current->files->fd. The corresponding index (the new file descriptor) is stored in the fd local variable. 3. Invokes the filp_open( ) function, passing as parameters the pathname, the access mode flags, and the permission bit mask. This function, in turn, executes the following steps: a. Copies the access mode flags into namei_flags, but encodes the access mode flags O_RDONLY, O_WRONLY, and O_RDWR with the format expected by the pathname lookup functions (see the earlier section Section 12.5). b. Invokes open_namei( ), passing to it the pathname, the modified access mode flags, and the address of a local nameidata data structure. The function performs the lookup operation in the following manner: ■ If O_CREAT is not set in the access mode flags, starts the lookup operation with the LOOKUP_PARENT flag not set. Moreover, the LOOKUP_FOLLOW flag is set only if O_NOFOLLOW is cleared, while the LOOKUP_DIRECTORY flag is set only if the O_DIRECTORY flag is set. ■ If O_CREAT is set in the access mode flags, starts the lookup operation with the LOOKUP_PARENT flag set. Once the path_walk( ) function successfully returns, checks whether the requested file already exists. If not, allocates a new disk inode by invoking the create method of the parent inode. The open_namei( ) function also executes several security checks on the file located by the lookup operation. For instance, the function checks whether the inode associated with the dentry object found really exists, whether it is a regular file, and whether the current process is allowed to access it according to the access mode flags. Also, if the file is opened for writing, the function checks that the file is not locked by other processes. c. Invokes the dentry_open( ) function, passing to it the access mode flags and the addresses of the dentry object and the mounted filesystem object located by the lookup operation. In turn, this function: 1. Allocates a new file object. 2. Initializes the f_flags and f_mode fields of the file object according to the access mode flags passed to the open( ) system call. 3. Initializes the f_fentry and f_vfsmnt fields of the file object according to the addresses of the dentry object and the mounted filesystem object passed as parameters. 4. Sets the f_op field to the contents of the i_fop field of the corresponding inode object. This sets up all the methods for future file operations. 5. Inserts the file object into the list of opened files pointed to by the s_files field of the filesystem's superblock. 6. If the O_DIRECT flag is set, preallocates a direct access buffer (see Section 15.3). 7. If the open method of the file operations is defined, invokes it. d. Returns the address of the file object. 4. Sets current->files->fd[fd] to the address of the file object returned by dentry_open( ). 5. Returns fd . 12.6.2 The read( ) and write( ) System Calls Let's return to the code in our cp example. The open( ) system calls return two file descriptors, which are stored in the inf and outf variables. Then the program starts a loop: at each iteration, a portion of the /floppy/TEST file is copied into a local buffer (read( ) system call), and then the data in the local buffer is written into the /tmp/test file (write( ) system call). The read( ) and write( ) system calls are quite similar. Both require three parameters: a file descriptor fd, the address buf of a memory area (the buffer containing the data to be transferred), and a number count that specifies how many bytes should be transferred. Of course, read( ) transfers the data from the file into the buffer, while write( ) does the opposite. Both system calls return either the number of bytes that were successfully transferred or -1 to signal an error condition. A return value less than count does not mean that an error occurred. The kernel is always allowed to terminate the system call even if not all requested bytes were transferred, and the user application must accordingly check the return value and reissue, if necessary, the system call. Typically, a small value is returned when reading from a pipe or a terminal device, when reading past the end of the file, or when the system call is interrupted by a signal. The End-Of-File condition (EOF) can easily be recognized by a null return value from read( ). This condition will not be confused with an abnormal termination due to a signal, because if read( ) is interrupted by a signal before any data is read, an error occurs. The read or write operation always takes place at the file offset specified by the current file pointer (field f_pos of the file object). Both system calls update the file pointer by adding the number of transferred bytes to it. In short, both sys_read( ) (the read( )'s service routine) and sys_write( ) (the write( )'s service routine) perform almost the same steps: 1. Invoke fget( ) to derive from fd the address file of the corresponding file object and increment the usage counter file->f_count. 2. Check whether the flags in file->f_mode allow the requested access (read or write operation). 3. Invoke locks_verify_area( ) to check whether there are mandatory locks for the file portion to be accessed (see Section 12.7 later in this chapter). 4. Invoke either file->f_op->read or file->f_op->write to transfer the data. Both functions return the number of bytes that were actually transferred. As a side effect, the file pointer is properly updated. 5. Invoke fput( ) to decrement the usage counter file->f_count. 6. Return the number of bytes actually transferred. 12.6.3 The close( ) System Call The loop in our example code terminates when the read( ) system call returns the value 0—that is, when all bytes of /floppy/TEST have been copied into /tmp/test. The program can then close the open files, since the copy operation has completed. The close( ) system call receives as its parameter fd, which is the file descriptor of the file to be closed. The sys_close( ) service routine performs the following operations: 1. Gets the file object address stored in current->files->fd[fd]; if it is NULL, returns an error code. 2. Sets current->files->fd[fd] to NULL. Releases the file descriptor fd by clearing the corresponding bits in the open_fds and close_on_exec fields of current->files (see Chapter 20 for the Close on Execution flag). 3. Invokes filp_close( ), which performs the following operations: a. Invokes the flush method of the file operations, if defined b. Releases any mandatory lock on the file c. Invokes fput( ) to release the file object 4. Returns the error code of the flush method (usually 0). I l@ve RuBoard I l@ve RuBoard 12.7 File Locking When a file can be accessed by more than one process, a synchronization problem occurs. What happens if two processes try to write in the same file location? Or again, what happens if a process reads from a file location while another process is writing into it? In traditional Unix systems, concurrent accesses to the same file location produce unpredictable results. However, Unix systems provide a mechanism that allows the processes to lock a file region so that concurrent accesses may be easily avoided. The POSIX standard requires a file-locking mechanism based on the fcntl( ) system call. It is possible to lock an arbitrary region of a file (even a single byte) or to lock the whole file (including data appended in the future). Since a process can choose to lock just a part of a file, it can also hold multiple locks on different parts of the file. This kind of lock does not keep out another process that is ignorant of locking. Like a critical region in code, the lock is considered "advisory" because it doesn't work unless other processes cooperate in checking the existence of a lock before accessing the file. Therefore, POSIX's locks are known as advisory locks. Traditional BSD variants implement advisory locking through the flock( ) system call. This call does not allow a process to lock a file region, just the whole file. Traditional System V variants provide the lockf( ) function, which is just an interface to fcntl( ). More importantly, System V Release 3 introduced mandatory locking: the kernel checks that every invocation of the open( ), read( ), and write( ) system calls does not violate a mandatory lock on the file being accessed. Therefore, mandatory locks are enforced even between noncooperative processes.[8] A file is marked as a candidate for mandatory locking by setting its set-group bit (SGID) and clearing the group-execute permission bit. Since the set-group bit makes no sense when the group-execute bit is off, the kernel interprets that combination as a hint to use mandatory locks instead of advisory ones. [8] Oddly enough, a process may still unlink (delete) a file even if some other process owns a mandatory lock on it! This perplexing situation is possible because when a process deletes a file hard link, it does not modify its contents, but only the contents of its parent directory. Whether processes use advisory or mandatory locks, they can use both shared read locks and exclusive write locks. Any number of processes may have read locks on some file region, but only one process can have a write lock on it at the same time. Moreover, it is not possible to get a write lock when another process owns a read lock for the same file region, and vice versa (see Table 12-18). Table 12-18. Whether a lock is granted Grant request for Current Locks Read lock? Write lock? No lock Yes Yes Read lock Yes No Write lock No No 12.7.1 Linux File Locking Linux supports all fashions of file locking: advisory and mandatory locks, as well as the fcntl( ), flock( ), and the lockf( ) system calls. However, the lockf( ) system call is just a library wrapper routine, and therefore is not discussed here. fcntl( )'s mandatory locks can be enabled and disabled on a per-filesystem basis using the MS_MANDLOCK flag (the mand option) of the mount( ) system call. The default is to switch off mandatory locking. In this case, fcntl( ) creates advisory locks. When the flag is set, fcntl( ) produces mandatory locks if the file has the set-group bit on and the group- execute bit off; it produces advisory locks otherwise. In earlier Linux versions, the flock( ) system call produced only advisory locks, without regard of the MS_MANDLOCK mount flag. This is the expected behavior of the system call in any Unix-like operating system. In Linux 2.4, however, a special kind of flock( )'s mandatory lock has been added to allow proper support for some proprietary network filesystem implementations. It is the so-called share-mode mandatory look; when set, no other process may open a file that would conflict with the access mode of the lock. Use of this feature for native Unix applications is discouraged, because the resulting source code will be nonportable. Another kind of flock( )-based mandatory lock called leases has been introduced in Linux 2.4. When a process tries to open a file protected by a lease, it is blocked as usual. However, the process that owns the lock receives a signal. Once informed, it should first update the file so that its content is consistent, and then release the lock. If the owner does not do this in a well-defined time interval (tunable by writing a number of seconds into /proc/sys/fs/lease-break-time, usually 45 seconds), the lease is automatically removed by the kernel and the blocked process is allowed to continue. Beside the checks in the read( ) and write( ) system calls, the kernel takes into consideration the existence of mandatory locks when servicing all system calls that could modify the contents of a file. For instance, an open( ) system call with the O_TRUNC flag set fails if any mandatory lock exists for the file. A lock produced by fcntl( ) is of type FL_POSIX, while a lock produced by flock( ) is of type FL_FLOCK, FL_MAND (for share-mode locks), or FL_LEASE (for leases). The types of locks produced by fcntl( ) may safely coexist with those produced by flock( ), but neither one has any effect on the other. Therefore, a file locked through fcntl( ) does not appear locked to flock( ), and vice versa. The following section describes the main data structure used by the kernel to handle file locks. The next two sections examine the differences between the two most common lock types: FL_POSIX and FL_FLOCK. 12.7.2 File-Locking Data Structures The file_lock data structure represents file locks; its fields are shown in Table 12-19. All file_lock data structures are included in a doubly linked list. The address of the first element is stored in file_lock_list, while the fields fl_nextlink and fl_prevlink store the addresses of the adjacent elements in the list. Table 12-19. The fields of the file_lock data structure Type Field Description struct file_lock * fl_next Next element in inode list struct list_head fl_link Pointers for global list struct list_head fl_block Pointers for process list struct files_struct * fl_owner Owner's files_struct unsigned int fl_pid PID of the process owner wait_queue_head_t fl_wait Wait queue of blocked processes struct file * fl_file Pointer to file object unsigned char fl_flags Lock flags unsigned char fl_type Lock type loff_t fl_start Starting offset of locked region loff_t fl_end Ending offset of locked region void (*)(struct file_lock *) fl_notify Function to call when lock is unblocked void (*)(struct file_lock *) fl_insert Function to call when lock is inserted void (*)(struct file_lock *) fl_remove Function to call when lock is removed struct fasync_struct * fl_fasync Used for lease break notifications union u Filesystem-specific information All lock_file structures that refer to the same file on disk are collected in a simply linked list, whose first element is pointed to by the i_flock field of the inode object. The fl_next field of the lock_file structure specifies the next element in the list. When a process tries to get an advisory or mandatory lock, it may be suspended until the previously allocated lock on the same file region is released. All processes sleeping on some lock are inserted into a wait queue, whose head is stored in the fl_wait field of the file_lock structure. Moreover, all processes sleeping on any file locks are inserted into a circular doubly linked list, whose head (first dummy element) is stored in the blocked_list variable; the fl_block field of the file_lock data structure stores the pointer to adjacent elements in the list. 12.7.3 FL_FLOCK Locks An FL_FLOCK lock is always associated with a file object and is thus maintained by a particular process (or clone processes sharing the same opened file). When a lock is requested and granted, the kernel replaces any other lock that the process is holding on the same file object. This happens only when a process wants to change an already owned read lock into a write one, or vice versa. Moreover, when a file object is being freed by the fput( ) function, all FL_FLOCK locks that refer to the file object are destroyed. However, there could be other FL_FLOCK read locks set by other processes for the same file (inode), and they still remain active. The flock( ) system call acts on two parameters: the fd file descriptor of the file to be acted upon and a cmd parameter that specifies the lock operation. A cmd parameter of LOCK_SH requires a shared lock for reading, LOCK_EX requires an exclusive lock for writing, and LOCK_UN releases the lock. If the LOCK_NB value is ORed to the LOCK_SH or LOCK_EX operation, the system call does not block; in other words, if the lock cannot be immediately obtained, the system call returns an error code. Note that it is not possible to specify a region inside the file—the lock always applies to the whole file. When the sys_flock( ) service routine is invoked, it performs the following steps: 1. Checks whether fd is a valid file descriptor; if not, returns an error code. Gets the address of the corresponding file object. 2. If the process has to acquire an advisory lock, checks that the process has both read and write permission on the open file; if not, returns an error code. 3. Invokes flock_lock_file( ), passing as parameters the file object pointer filp, the type type of lock operation required, and a flag wait. This last parameter is set if the system call should block (LOCK_NB clear) and cleared otherwise (LOOK_NB set). This function performs, in turn, the following actions: a. If the lock must be acquired, gets a new file_lock object and fills it with the appropriate lock operation. b. Searches the list that filp->f_dentry->d_inode->i_flock points to. If an FL_FLOCK lock for the same file object is found and an unlock operation is required, removes the file_lock element from the inode list and the global list, wakes up all processes sleeping in the lock's wait queue, frees the file_lock structure, and returns. c. Otherwise, searches the inode list again to verify that no existing FL_FLOCK lock conflicts with the requested one. There must be no FL_FLOCK write lock in the inode list, and moreover, there must be no FL_FLOCK lock at all if the processing is requesting a write lock. However, a process may want to change the type of lock it already owns; this is done by issuing a second flock( ) system call. Therefore, the kernel always allows the process to change locks that refer to the same file object. If a conflicting lock is found and the LOCK_NB flag was specified, the function returns an error code; otherwise, it inserts the current process in the circular list of blocked processes and suspends it. d. If no incompatibility exists, inserts the file_lock structure into the global lock list and the inode list, and then returns 0 (success). 4. Returns the return code of flock_lock_file( ). 12.7.4 FL_POSIX Locks An FL_POSIX lock is always associated with a process and with an inode; the lock is automatically released either when the process dies or when a file descriptor is closed (even if the process opened the same file twice or duplicated a file descriptor). Moreover, FL_POSIX locks are never inherited by the child across a fork( ). When used to lock files, the fcntl( ) system call acts on three parameters: the fd file descriptor of the file to be acted upon, a cmd parameter that specifies the lock operation, and an fl pointer to a flock data structure. Version 2.4 of Linux also defines a flock64 structure, which uses 64-bit fields for the file offset and length fields. In the following, we focus on the flock data structure, but the description is valid for flock64 too. Locks of type FL_POSIX are able to protect an arbitrary file region, even a single byte. The region is specified by three fields of the flock structure. l_start is the initial offset of the region and is relative to the beginning of the file (if field l_whence is set to SEEK_SET), to the current file pointer (if l_whence is set to SEEK_CUR), or to the end of the file (if l_whence is set to SEEK_END). The l_len field specifies the length of the file region (or 0, which means that the region includes all potential writes past the current end of the file). The sys_fcntl( ) service routine behaves differently, depending on the value of the flag set in the cmd parameter: F_GETLK Determines whether the lock described by the flock structure conflicts with some FL_POSIX lock already obtained by another process. In this case, the flock structure is overwritten with the information about the existing lock. F_SETLK Sets the lock described by the flock structure. If the lock cannot be acquired, the system call returns an error code. F_SETLKW Sets the lock described by the flock structure. If the lock cannot be acquired, the system call blocks; that is, the calling process is put to sleep. F_GETLK64, F_SETLK64, F_SETLKW64 Identical to the previous ones, but the flock64 data structure is used rather than flock. When sys_fcntl( ) acquires a lock, it performs the following: 1. Reads the flock structure from user space. 2. Gets the file object corresponding to fd. 3. Checks whether the lock should be a mandatory one and the file has a shared memory mapping (see Chapter 15). In this case, refuses to create the lock and returns the -EAGAIN error code; the file is already being accessed by another process. 4. Initializes a new file_lock structure according to the contents of the user's flock structure. 5. Terminates returning an error code if the file does not allow the access mode specified by the type of the requested lock. 6. Invokes the lock method of the file operations, if defined. 7. Invokes the posix_lock_file( ) function, which executes the following actions: a. Invokes posix_locks_conflict( ) for each FL_POSIX lock in the inode's lock list. The function checks whether the lock conflicts with the requested one. Essentially, there must be no FL_POSIX write lock for the same region in the inode list, and there may be no FL_POSIX lock at all for the same region if the process is requesting a write lock. However, locks owned by the same process never conflict; this allows a process to change the characteristics of a lock it already owns. b. If a conflicting lock is found and fcntl( ) was invoked with the F_SETLK or F_SETLK64 flag, returns an error code. Otherwise, the current process should be suspended. In this case, invokes posix_locks_deadlock( ) to check that no deadlock condition is being created among processes waiting for FL_POSIX locks, and then inserts the current process in the circular list of blocked processes and suspends it. c. As soon as the inode's lock list includes no conflicting lock, checks all the FL_POSIX locks of the current process that overlap the file region that the current process wants to lock, and combines and splits adjacent areas as required. For example, if the process requested a write lock for a file region that falls inside a read-locked wider region, the previous read lock is split into two parts covering the nonoverlapping areas, while the central region is protected by the new write lock. In case of overlaps, newer locks always replace older ones. d. Inserts the new file_lock structure in the global lock list and in the inode list. 8. Returns the value 0 (success). I l@ve RuBoard I l@ve RuBoard Chapter 13. Managing I/O Devices The Virtual File System in the last chapter depends on lower-level functions to carry out each read, write, or other operation in a manner suited to each device. The previous chapter included a brief discussion of how operations are handled by different filesystems. In this chapter, we look at how the kernel invokes the operations on actual devices. In Section 13.1, we give a brief survey of the 80 x 86 I/O architecture. In Section 13.2, we show how the VFS associates a special file called "device file" with each different hardware device so that application programs can use all kinds of devices in the same way. Finally, in Section 13.3, we illustrate the overall organization of device drivers in Linux. Readers interested in developing device drivers on their own may want to refer to Alessandro Rubini and Jonathan Corbet's Linux Device Drivers (O'Reilly). I l@ve RuBoard I l@ve RuBoard 13.1 I/O Architecture To make a computer work properly, data paths must be provided that let information flow between CPU(s), RAM, and the score of I/O devices that can be connected to a personal computer. These data paths, which are denoted collectively as the bus, act as the primary communication channel inside the computer. Several types of buses, such as the ISA, EISA, PCI, and MCA, are currently in use. In this section, we discuss the functional characteristics common to all PC architectures, without giving details about a specific bus type. In fact, what is commonly denoted as a bus consists of three specialized buses: Data bus A group of lines that transfer data in parallel. The Pentium has a 64-bit-wide data bus. Address bus A group of lines that transmits an address in parallel. The Pentium has a 32-bit-wide address bus. Control bus A group of lines that transmits control information to the connected circuits. The Pentium uses control lines to specify, for instance, whether the bus is used to allow data transfers between a processor and the RAM, or alternatively, between a processor and an I/O device. Control lines also determine whether a read or a write transfer must be performed. When the bus connects the CPU to an I/O device, it is called an I/O bus. In this case, 80 x 86 microprocessors use 16 out of the 32 address lines to address I/O devices and 8, 16, or 32 out of the 64 data lines to transfer data. The I/O bus, in turn, is connected to each I/O device by means of a hierarchy of hardware components including up to three elements: I/O ports, interfaces, and device controllers. Figure 13-1 shows the components of the I/O architecture. Figure 13-1. PC's I/O architecture 13.1.1 I/O Ports Each device connected to the I/O bus has its own set of I/O addresses, which are usually called I/O ports. In the IBM PC architecture, the I/O address space provides up to 65,536 8- bit I/O ports. Two consecutive 8-bit ports may be regarded as a single 16-bit port, which must start on an even address. Similarly, two consecutive 16-bit ports may be regarded as a single 32-bit port, which must start on an address that is a multiple of 4. Four special assembly language instructions called in, ins, out, and outs allow the CPU to read from and write into an I/O port. While executing one of these instructions, the CPU uses the address bus to select the required I/O port and of the data bus to transfer data between a CPU register and the port. I/O ports may also be mapped into addresses of the physical address space. The processor is then able to communicate with an I/O device by issuing assembly language instructions that operate directly on memory (for instance, mov, and, or, and so on). Modern hardware devices are more suited to mapped I/O, since it is faster and can be combined with DMA. An important objective for system designers is to offer a unified approach to I/O programming without sacrificing performance. Toward that end, the I/O ports of each device are structured into a set of specialized registers, as shown in Figure 13-2. The CPU writes the commands to be sent to the device into the control register and reads a value that represents the internal state of the device from the status register. The CPU also fetches data from the device by reading bytes from the input register and pushes data to the device by writing bytes into the output register. Figure 13-2. Specialized I/O ports To lower costs, the same I/O port is often used for different purposes. For instance, some bits describe the device state, while others specify the command to be issued to the device. Similarly, the same I/O port may be used as an input register or an output register. 13.1.1.1 Accessing I/O ports The in, out, ins, and outs assembly language instructions access I/O ports. The following auxiliary functions are included in the kernel to simplify such accesses: inb( ), inw( ), inl( ) Read 1, 2, or 4 consecutive bytes, respectively, from an I/O port. The suffix "b," "w," or "l" refers, respectively, to a byte (8 bits), a word (16 bits), and a long (32 bits). inb_p( ) inw_p( ), inl_p( ) Read 1, 2, or 4 consecutive bytes, respectively, from an I/O port, and then execute a "dummy" instruction to introduce a pause. outb( ), outw( ), outl( ) Write 1, 2, or 4 consecutive bytes, respectively, to an I/O port. outb_p( ), outw_p( ), outl_p( ) Write 1, 2, and 4 consecutive bytes, respectively, to an I/O port, and then execute a "dummy" instruction to introduce a pause. insb( ), insw( ), insl( ) Read sequences of consecutive bytes in groups of 1, 2, or 4, respectively, from an I/O port. The length of the sequence is specified as a parameter of the functions. outsb( ), outsw( ), outsl( ) Write sequences of consecutive bytes, in groups of 1, 2, or 4, respectively, to an I/O port. While accessing I/O ports is simple, detecting which I/O ports have been assigned to I/O devices may not be easy, in particular, for systems based on an ISA bus. Often a device driver must blindly write into some I/O port to probe the hardware device; if, however, this I/O port is already used by some other hardware device, a system crash could occur. To prevent such situations, the kernel keeps track of I/O ports assigned to each hardware device by means of "resources." A resource represents a portion of some entity that can be exclusively assigned to a device driver. In our case, a resource represents a range of I/O port addresses. The information relative to each resource is stored in a resource data structure, whose fields are shown in Table 13-1. All resources of the same kind are inserted in a tree-like data structure; for instance, all resources representing I/O port address ranges are included in a tree rooted at the node ioport_resource. Table 13-1. The fields of the resource data structure Type Field Description const char * name Description of owner of the resource unsigned long start Start of the resource range unsigned long end End of the resource range unsigned long flags Various flags struct resource * parent Pointer to parent in the resource tree struct resource * sibling Pointer to a sibling in the resource tree struct resource * child Pointer to first child in the resource tree The children of a node are collected in a list whose first element is pointed to by the child field. The sibling field points to the next node in the list. Why use a tree? Well, consider, for instance, the I/O port addresses used by an IDE hard disk interface—let's say from 0xf000 to 0xf00f. A resource with the start field set to 0xf000 and the end field set to 0xf00f is then included in the tree, and the conventional name of the controller is stored in the name field. However, the IDE device driver needs to remember another bit of information, namely that the subrange from 0xf000 to 0xf007 is used for the master disk of the IDE chain, while the subrange from 0xf008 to 0xf00f is used for the slave disk. To do this, the device driver inserts two children below the resource corresponding to the whole range from 0xf000 to 0xf00f, one child for each subrange of I/O ports. As a general rule, each node of the tree must correspond to a subrange of the range associated with the parent. Any device driver may use the following three functions, passing to them the root node of the resource tree and the address of a resource data structure of interest: request_resource( ) Assigns a given range to an I/O device. check_resource( ) Checks whether a given range is free or whether some subrange has already been assigned to an I/O device release_resource( ) Releases a given range previously assigned to an I/O device. The kernel also defines some shortcuts to the above functions that apply to I/O ports: request_region( ) assigns a given interval of I/O ports, check_region( ) verifies whether a given interval of I/O ports is free or (even partially) busy, and release_region( ) releases a previously assigned interval of I/O ports. The tree of all I/O addresses currently assigned to I/O devices can be obtained from the /proc/ioports file. 13.1.2 I/O Interfaces An I/O interface is a hardware circuit inserted between a group of I/O ports and the corresponding device controller. It acts as an interpreter that translates the values in the I/O ports into commands and data for the device. In the opposite direction, it detects changes in the device state and correspondingly updates the I/O port that plays the role of status register. This circuit can also be connected through an IRQ line to a Programmable Interrupt Controller, so that it issues interrupt requests on behalf of the device. There are two types of interfaces: Custom I/O interfaces Devoted to one specific hardware device. In some cases, the device controller is located in the same card [1] that contains the I/O interface. The devices attached to a custom I/O interface can be either internal devices (devices located inside the PC's cabinet) or external devices (devices located outside the PC's cabinet). [1] Each card must be inserted in one of the available free bus slots of the PC. If the card can be connected to an external device through an external cable, the card sports a suitable connector in the rear panel of the PC. General-purpose I/O interfaces Used to connect several different hardware devices. Devices attached to a general- purpose I/O interface are always external devices. 13.1.2.1 Custom I/O interfaces Just to give an idea of how much variety is encompassed by custom I/O interfaces — thus by the devices currently installed in a PC — we'll list some of the most commonly found: Keyboard interface Connected to a keyboard controller that includes a dedicated microprocessor. This microprocessor decodes the combination of pressed keys, generates an interrupt, and puts the corresponding scan code in an input register. Graphic interface Packed together with the corresponding controller in a graphic card that has its own frame buffer, as well as a specialized processor and some code stored in a Read-Only Memory chip (ROM). The frame buffer is an on-board memory containing a description of the current screen contents. Disk interface Connected by a cable to the disk controller, which is usually integrated with the disk. For instance, the IDE interface is connected by a 40-wire flat conductor cable to an intelligent disk controller that can be found on the disk itself. Bus mouse interface Connected by a cable to the corresponding controller, which is included in the mouse. Network interface Packed together with the corresponding controller in a network card used to receive or transmit network packets. Although there are several widely adopted network standards, Ethernet (IEEE 802.3) is the most common. 13.1.2.2 General-purpose I/O interfaces Modern PCs include several general-purpose I/O interfaces, which connect a wide range of external devices. The most common interfaces are: Parallel port Traditionally used to connect printers, it can also be used to connect removable disks, scanners, backup units, and other computers. The data is transferred 1 byte (8 bits) at a time. Serial port Like the parallel port, but the data is transferred 1 bit at a time. It includes a Universal Asynchronous Receiver and Transmitter (UART) chip to string out the bytes to be sent into a sequence of bits and to reassemble the received bits into bytes. Since it is intrinsically slower than the parallel port, this interface is mainly used to connect external devices that do not operate at a high speed, like modems, mouses, and printers. Universal serial bus (USB) A recent general-purpose I/O interface that is quickly gaining popularity. It operates at a high speed, and may be used for the external devices traditionally connected to the parallel port and the serial port. PCMCIA interface Included mostly on portable computers. The external device, which has the shape of a credit card, can be inserted into and removed from a slot without rebooting the system. The most common PCMCIA devices are hard disks, modems, network cards, and RAM expansions. SCSI (Small Computer System Interface) interface A circuit that connects the main PC bus to a secondary bus called the SCSI bus. The SCSI-2 bus allows up to eight PCs and external devices—hard disks, scanners, CD- ROM writers, and so on—to be connected. Wide SCSI-2 and the recent SCSI-3 interfaces allow you to connect 16 devices or more if additional interfaces are present. The SCSI standard is the communication protocol used to connect devices via the SCSI bus. 13.1.3 Device Controllers A complex device may require a device controller to drive it. Essentially, the controller plays two important roles: ● It interprets the high-level commands received from the I/O interface and forces the device to execute specific actions by sending proper sequences of electrical signals to it. ● It converts and properly interprets the electrical signals received from the device and modifies (through the I/O interface) the value of the status register. A typical device controller is the disk controller, which receives high-level commands such as a "write this block of data" from the microprocessor (through the I/O interface) and converts them into low-level disk operations such as "position the disk head on the right track" and "write the data inside the track." Modern disk controllers are very sophisticated, since they can keep the disk data in fast memory caches and can reorder the CPU high-level requests optimized for the actual disk geo