Tuning the I/O Stack
local graph
Chapter 11 — Tuning the I/O Stack
Section titled “Chapter 11 — Tuning the I/O Stack”Well, here we are at the end of our journey. Just because you are reading the introduction of the final chapter does not mean that you’ve read through the entire book, but I’ll take my chances. If you’ve indeed followed us along, then I hope your journey was worth it and has left you yearning for more.
Getting back to brass tacks, the previous two chapters centered on the performance analysis of the I/O stack. Chapter 9 focused on the most common disk metrics and the tools that can help us to identify performance bottlenecks in physical disks. In any performance analysis, the physical disks come under far more scrutiny than any other layer, which can sometimes be misleading. Therefore, in Chapter 10, we saw how we can investigate the higher layers in the I/O stack, such as filesystems and the block layer.
This brings us to the next logical step in our quest. Once we’ve identified the elements plaguing our environment, what steps can we take to mitigate those limitations? It is important to have specific goals for the desired tuning outcomes because, at the end of the day, performance tuning is a trade-off between choices. For instance, tuning the system for low latency may reduce its overall throughput. A performance baseline should first be determined, and any tweaks or adjustments should be carried out in small sets. This chapter will deal with the different tweaks that can be applied to improve I/O performance.
Here’s an outline of what follows:
- How memory usage affects I/O
- Tuning the memory subsystem
- Tuning the filesystem
- Choosing the right scheduler
Technical requirements
Section titled “Technical requirements”The material presented in this chapter builds on the concepts discussed in preceding chapters. If you’ve followed along and have become familiar with the functions of each layer in the disk I/O hierarchy, you’ll find this chapter much easier to follow. If you have a prior understanding of memory management in Linux, that will be a huge plus.
The commands and examples presented in this chapter are distribution-agnostic and can be run on any Linux operating system, such as Debian, Ubuntu, Red Hat, or Fedora. There are quite a few references to the kernel source code. If you want to download the kernel source, you can download it from https://www.kernel.org.
How memory usage affects I/O
Section titled “How memory usage affects I/O”As we’ve seen, VFS serves as an entry point for our I/O requests and includes different types of caches, the most important of which is the page cache. The purpose of page cache is to improve I/O performance and minimize the expense of I/O as generated by swapping and file system operations, thus avoiding unnecessary trips to the underlying physical disks. Although we haven’t explored it in these pages, it is important to have an idea about how the kernel goes about managing its memory management subsystem. The memory management subsystem is also referred to as the virtual memory manager (VMM). Some of the responsibilities of the virtual memory manager include the following:
- Managing the allocation of physical memory for all the user space and kernel space applications
- Implementation of virtual memory and demand paging
- The mapping of files into processes address space
- Freeing up memory in case of shortage, either by pruning or swapping caches
As it’s often said, the best I/O is the one that is avoided. The kernel follows this approach and makes generous allocation of the free memory, filling it up with the different types of caches. The greater the amount of free memory available, the more effective the caching mechanism. This all works well for general use cases, where applications perform small-scale requests and there is a relative amount of page caches available:

Figure 11.1 – A page cache can speed up I/O performance
Conversely, if memory is scarcely available, not only will the caches be pruned regularly but the data might also get swapped out to disk, which will ultimately hurt performance. The kernel works under the temporal locality principle, meaning that the recently accessed blocks of data are more likely to be accessed again. This is generally good for most cases. It could take a few milliseconds to read data from a random part of the disk, whereas accessing that same data from memory if it is cached only takes a few nanoseconds. Therefore, any request that can be readily served from the page cache minimizes the cost of an I/O operation.
Tuning the memory subsystem
Section titled “Tuning the memory subsystem”It’s a bit strange that how Linux deals with memory can have a major say in disk performance memory. As already explained, the default behavior of the kernel works well in most cases. However, as they say, an excess of everything is bad. Frequent caching can result in a few problematic scenarios:
- When the kernel has accumulated a large amount of data in the page cache and eventually starts to flush that data onto disk, the disk will remain busy for quite some time because of the excessive write operations. This can adversely affect the overall I/O performance and increase disk response times.
- The kernel does not have a sense of the criticality of the data in the page cache. Hence, it does not distinguish between important and unimportant I/O. The kernel picks whichever block of data it deems appropriate and schedules it for a write or read operation. For instance, if an application performs both background and foreground I/O operations, then usually, the priority of the foreground operations should be higher. However, I/O belonging to background tasks can overwhelm foreground tasks.
The cache provided by the kernel usually enables applications to obtain better performance when reading and writing data, but the algorithms used by the page cache are not designed for a particular application; they are designed to be general-purpose. In most cases, this default behavior would work just fine, but in some cases, this can backfire. For some self-caching applications, such as database management systems, this approach might not offer the best results. Applications such as databases have a better understanding of the way data is organized internally. Hence, these systems prefer to have their own caching mechanism to improve read and write performance.
Using direct I/O
Section titled “Using direct I/O”If data is cached directly at the application level, then moving data from disk to the page cache and back to the application’s cache will constitute a significant overhead, resulting in more CPU and memory usage. In such scenarios, it might be desirable to bypass the kernel’s page cache altogether and leave the responsibility of caching to the application. This is known as direct I/O.
Using direct I/O, all the file reads and writes go directly from the application to the storage device, bypassing the kernel’s page cache. The Unix filesystem (UFS) filesystem (not supported in Linux) includes direct I/O as filesystem parameters, which can be specified while mounting the filesystem. In Linux, direct I/O is not a filesystem parameter, nor is there a command to enable it. Instead, it is the responsibility of an application to initiate direct I/O. The application can invoke direct I/O by using the O_DIRECT flag on a system call, such as open (). The O_DIRECT flag is only a status flag (represented by DIR), which is passed by the application while opening or creating a file so that it can go around the page cache of the kernel:

Figure 11.2 – The different ways of performing I/O
It doesn’t make sense to use direct I/O for regular applications, as it can cause performance deterioration. However, for self-caching applications, it can offer significant gains. The recommended method is to check the status of direct I/O via an application. However, if you want to check via the command line, use the lsof command to check the flags through which a file is opened.

Figure 11.3 – Checking direct I/O
For files opened by the application through the O_DIRECT flag, the FILE-FLAG column of the output will include the DIR flag.
The performance gains from direct I/O come from avoiding the CPU cost of copying data from disk into the page cache, and from steering clear of the double buffering, once in the application and once in the filesystem.
Controlling the write-back frequency
Section titled “Controlling the write-back frequency”As already explained, caching has its advantages, as it accelerates many accesses to files. Once most of the free memory has been occupied by the cache, the kernel has to make a decision on how to free memory in order to entertain incoming I/O operations. Using the Least Recently Used (LRU) approach, the kernel does two things – it evicts old data from the page cache and even offloads some of it to the swap area, in order to make room for incoming requests.
Again, it all comes down to the specifics. The default approach is good enough, and that is exactly how the kernel should go about making room for incoming data. However, consider the following scenarios:
- What if the data currently in the cache won’t be accessed again in the future? This is true for most backup operations. A backup operation will read and write a lot of data from the disk, which will be cached by the kernel. However, it is unlikely that this data, which is present in the cache, will be accessed in the near future. However, the kernel will keep this data in the cache and might evict the older pages, which had a greater probability of being accessed again.
- Swapping data to disk will generate a lot of disk I/O, which won’t be good for performance.
- When a large amount of data has been cached, a system crash can result in a major loss of data. This can be a significant concern if data is of a sensitive nature.
It’s not possible to disable the page cache. Even if there was, it’s not something that should be done. There are, however, a number of parameters that can be tweaked to control its behavior. As shown here, there are several parameters that can be controlled through the sysctl interface:
[root@linuxbox ~]# sysctl -a | grep dirtyvm.dirty_background_ratio = 10vm.dirty_background_bytes = 0vm.dirty_ratio = 20vm.dirty_bytes = 0vm.dirty_writeback_centisecs = 500vm.dirty_expire_centisecs = 3000Let us look at them in detail:
vm.dirty_background_ratio: The write-back flusher threads initiate the flushing of dirty pages to disk when the percentage of dirty pages in the cache surpasses a certain threshold. Prior to this threshold, no pages are written to the disk. Once flushing begins, it occurs in the background without causing any disturbance to the foreground processes.vm.dirty_ratio: This refers to the threshold of system memory utilization, beyond which the writing process gets blocked and dirty pages are written out to the disk.
For large memory systems, hundreds of GB of data can be flushed from the page cache to disk, which will cause noticeable delays and adversely affect not only the disk’s performance but also overall system performance. In such cases, lowering these values might be helpful, as data will be flushed to disk on a regular basis, avoiding the write storm.
You can check the current values of these parameters using sysctl – for instance, if the values are as follows:
vm.dirty_background_ratio=10vm.dirty_ratio=20Think of vm.dirty_ratio as the upper limit. Using these previously mentioned values means that when the percentage of dirty pages in the cache reaches 10%, the background threads are triggered to write them to the disk. However, when the total number of dirty pages in the cache exceeds 20%, all writes are blocked until a portion of the dirty pages are written to the disk. These two parameters have the following two counterparts:
vm.dirty_background_bytes: This denotes the amount of dirty memory, expressed in bytes, that triggers the background flusher threads to initiate writing back to the disk. This is the counterpart ofvm.dirty_background_ratio, and only one of them can be configured. The value can be defined either as a percentage or a precise number of bytes.vm.dirty_bytes: This is the amount of dirty memory, expressed in bytes, that results in the writing process getting blocked and writing out the dirty pages to the disk. This controls the same tunable asvm.dirty_ratio, and only one of them can be set.vm.dirty_expire_centisecs: This indicates how long something can be in the cache before it needs to be written. This tunable specifies the age at which the dirty data is deemed suitable for write-back by the flusher threads. The time duration is measured in hundredths of a second.
To summarize, the default behavior of the kernel’s page cache works well most of the time, and usually, it won’t require any tweaking. However, for intelligent applications such as large-scale databases, the frequent caching of data can become a hurdle. Fortunately, there are a few workarounds available. Such applications can be configured to use direct I/O, which will bypass the page cache. The kernel also offers several parameters that can be used to tweak the behavior of the page cache. However, it is important to note that changing these values can result in increased I/O traffic. Therefore, workload-specific testing should be conducted prior to making changes.
Tuning the filesystem
Section titled “Tuning the filesystem”As we focus on tuning the different components that can impact I/O performance, we’ll try to steer our conversation away from the hardware side of things. Given the advancements in hardware, upgrading the memory, compute, network, and storage apparatus is bound to add at least some level of performance gains. However, most of the time, the magnitude of those gains will be limited. You need a well-designed and configured software stack to take advantage of that hardware. As we’re not focusing on a particular type of application, we’ll try to present some general tweaks that can be used to fine-tune your I/O. Again, note that the parameters that will be presented here or were discussed earlier require thorough testing and may not offer the same results in different environments.
Coming back to the topic of our discussion, filesystems are responsible for organizing data on disk and are the point of contact for an application to perform I/O. This makes them an ideal candidate for the tuning and troubleshooting process. Some applications explicitly mention the filesystem that should be used for optimal performance. As Linux supports different flavors of filesystems that use different techniques to store user data, some mount options might not be common among filesystems.
Block size
Section titled “Block size”Filesystems address physical storage in terms of blocks. A block is a group of physical sectors and is the fundamental unit of I/O for a filesystem. Each file in the filesystem will occupy at least one block, even if the file contains nothing. By default, a block size of 4 KB is used for most filesystems. If the application mostly creates a large number of small-sized files in the filesystem, typically of a few bytes or less than a couple of KB, then it is best to use smaller block sizes than the default value of 4 KB.
Filesystems perform better if applications use the same read and write size as the block size, or use a size that is a multiple of the block size. The block size for a filesystem can only be specified during its creation and cannot be changed afterward. Therefore, the block size needs to be decided before creating the filesystem.
Filesystem I/O alignment
Section titled “Filesystem I/O alignment”The concept of I/O alignment is generally overlooked, but this can have a huge impact on the filesystem performance. This is especially true for the complex enterprise storage systems of today, which consist of flash drives that have different page sizes and some form of RAID configuration on top of them.
The I/O alignment for filesystems is concerned with how data is distributed and organized across the filesystem. That’s one side of the coin. If the underlying physical storage consists of a striped RAID configuration, the data should be aligned with the underlying storage geometry for optimal performance. For instance, for a RAID device with a 64 K per-disk stripe size and 10 data-bearing disks, the filesystem should be created as follows:
- For XFS, it should be the following:
mkfs.xfs -f -d su=64k,sw=10 /dev/sdXXFS provides two sets of tunables in this regard. Depending on the specification units that you’ve set, you can use these:
Sunit: A stripe unit, in 512-byte blocksswidth: A stripe width, in 512-byte blocks
Alternatively, you can use these:
su: A per-disk stripe unit, in K if suffixed with ksw: A stripe width, by the number of data disks- For Ext4, the command would look as follows:
mkfs.ext4 -E stride=16,stripe-width=160 /dev/sdXExt4 also provides a couple of tunables, which can be used as follows:
stride: The number of filesystem blocks on each data-bearing disk in that stripestripe-width: The total stripe-width in filesystem blocks, equal to (stride) x (the number of data-bearing disks)
LVM I/O alignment
Section titled “LVM I/O alignment”Every abstraction layer created on top of a RAID device must be aligned to a multiple of Stripe Width, plus any required initial alignment offset. This ensures that a read or write request of a single block at the filesystem will not span the RAID stripe boundaries and cause multiple stripes to be read and written at the disk level, adversely affecting performance.
The first physical extent allocated within the physical volume should be aligned to a multiple of the RAID Stripe Width. If the physical volume is created directly on a raw disk, then it should also be offset by any required initial alignment offset. To check where the physical extents start, use the following:
pvs -o +pe_startHere, pe_start refers to the first physical extent.
The logical volumes are always allocated a contiguous range of physical extents when possible. If a contiguous range doesn’t exist, non-contiguous ranges might be allocated. Since a non-contiguous range of extents can impact performance, there is an option (--contiguous) while creating a logical volume to prevent the non-contiguous allocation of extents.
Journaling
Section titled “Journaling”As explained in Chapter 3, the concept of journaling guarantees data consistency and integrity if I/O operations on a filesystem fail due to external events. Any changes that need to be performed on the filesystem are first written to a journal. Once data has been written to a journal, it is then written to the appropriate location on the disk. If there is a system crash, the filesystem replays the journal to see if any operation was left in an incomplete state. This reduces the likelihood that the filesystem will become corrupted if there are any hardware failures.
Apparently, the journaling approach adds extra overhead and can potentially affect filesystem performance. However, given the sequential nature of journal writes, the filesystem performance is not affected. So, it is recommended to keep the filesystem journal enabled to ensure data integrity.
It is, however, recommended to change the mode of the filesystem journal to suit your needs. Most filesystems don’t have multiple journaling modes but Ext4 offers a great deal of flexibility in this regard. The Ext4 offers three journaling modes. Among them, the write-back mode offers considerably better performance than the ordered and data mode. The write-back mode only journals the metadata and does not follow any order when writing the data and metadata to disk. The ordered mode on the other hand follows a strict order and first writes the actual data before the metadata. The data mode offers the lowest performance, as it has to write both the data and metadata to a journal, resulting in twice the number of operations.
Another thing that can be done to improve journaling is to use an external journal. The default location for a filesystem journal is on the same block device as the data. If the I/O workload is metadata-intensive and the synchronous metadata writes to the journal must complete successfully before any associated data writes can start, this can result in I/O contention and may impact performance. In such cases, it can be a good idea to use an external device for filesystem journaling. The journal size is typically very small and requires very little storage space. The external journal should ideally be placed on fast physical media with a battery-backed write-back cache.
Barriers
Section titled “Barriers”As mentioned earlier, most filesystems make use of journaling to keep track of changes that have not yet been written to disk. A write barrier is a kernel mechanism that guarantees the proper ordering and accurate writing of filesystem metadata onto persistent storage, even if storage devices with unstable write caches lose power. Write barriers enforce proper on-disk ordering of journal commits by forcing the storage device to flush its cache at certain intervals. This makes volatile write caches safe to use, but it can incur some performance deficit. If the storage device cache is battery-backed, disabling filesystem barriers may offer some performance improvement.
Timestamps
Section titled “Timestamps”The kernel records information about when files were created (ctime) and last modified (mtime),as well as when they were last accessed (atime). If an application frequently modifies a bunch of files, then their corresponding timestamps will need to be updated every time. Performing these modifications also requires I/O operations, and when there are too many of them, there is a cost associated with them.
To mitigate this, there is a special mount option for filesystems called noatime. When a filesystem is mounted with the noatime option, reading from the filesystem will not update the file’s atime information. The noatime setting is significant, as it removes the requirement for a system to perform writes to the filesystem for files that are only read. This can lead to noticeable performance improvements, since write operations can be expensive.
Read-ahead
Section titled “Read-ahead”The read-ahead functionality in filesystems can enhance file access performance by proactively fetching data that is expected to be required soon and storing it in the page cache, which allows for faster access compared to retrieving the data from the disk. A higher read-ahead value indicates that the system will prefetch data further ahead of the current read position. This is especially true for sequential workloads.
Discarding unused blocks
Section titled “Discarding unused blocks”As we explained in Chapter 8, in SSDs, a write operation can be done at the page level, but the erase operation always affects entire blocks. As a result, writing data to SSDs is very fast as long as empty pages can be used. However, once previously written pages need to be overwritten, the writes slow down considerably, impacting performance. The trim command tells the SSD to discard the blocks that are no longer needed and can be deleted. The filesystem is the only component in the I/O stack that knows the parts of the SSD that should be trimmed. Most filesystems offer mount parameters that implement this feature.
To summarize, filesystems, to a certain extent, map logical addresses to physical addresses. When an application writes data, the filesystem decides how to distribute writes properly in order to make the best use of the underlying physical storage. This makes filesystems a very important layer when it comes to performance tuning. Most of the changes in filesystems cannot be done on the fly; they’re either performed during filesystem creation or require unmounting and remounting the filesystem. So, the decision regarding the choice of filesystem parameters should be made in advance, as changing things afterward can be a disruptive activity.
Choosing the right scheduler
Section titled “Choosing the right scheduler”The sole purpose of I/O schedulers is to optimize disk access requests. There are some common techniques used by schedulers, such as merging I/O requests that are adjacent on disk. The idea is to avoid frequent trips to the physical storage. Aggregating requests that are situated in close proximity on the disk reduces the frequency of the drive’s seeking operations, thereby enhancing the overall response time of disk operations. I/O schedulers aim to optimize throughput by rearranging access requests into sequential order. However, this strategy may cause some I/O requests to wait for an extended time, resulting in latency problems in certain situations. I/O schedulers strive to achieve a balance between maximizing throughput and distributing I/O requests equitably among all processes. As with all other things, Linux has a variety of I/O schedulers available. Each has its own set of strengths:
| Use case | Recommended I/O scheduler |
|---|---|
| Desktop GUI, interactive applications, and soft real-time applications, such as audio and video players | Budget Fair Queuing (BFQ), as it guarantees good system responsiveness and a low latency for time-sensitive applications |
| Traditional mechanical drives | BFQ or Multiqueue (MQ)-Deadline – both are considered suitable for slower drives. Kyber/none are biased in favor of faster disks. |
| High-performing SSDs and NVMe drives as local storage | Preferable none, but Kyber might also be a good alternative in some cases |
| Enterprise storage arrays | None, as most storage arrays have built-in logic to schedule I/Os more efficiently |
| Virtualized environments | MQ-Deadline is a good option. If the hypervisor layer does its own I/O scheduling, then using the none scheduler might be beneficial, |
Table 11.1 – Some use cases for I/O schedulers
The good thing is that an I/O scheduler can be changed on the fly. It is also possible to use a different I/O scheduler for every storage device on the system. A good starting point to select or fine-tune an I/O scheduler is to determine the system’s purpose or role. It is generally accepted that there is no single I/O scheduler that can meet all of a system’s diverse I/O demands.
Summary
Section titled “Summary”After having spent two chapters trying to diagnose and analyze the performance of different layers in the I/O stack, this chapter focused on the performance-tuning aspect of the I/O stack. Throughout this book, we’ve familiarized ourselves with the multi-level hierarchy of the I/O stack and built an understanding of the components that can impact the overall I/O performance.
We started this chapter by briefly going through the functions of the memory subsystem and how it can impact the I/O performance of a system. As all write operations are, by default, first performed in the page cache, the way the page cache is configured to behave can have a major say in an application’s I/O performance. We also explained the concept of direct I/O and defined some of the different parameters that can be used to tweak the write-back cache.
We also looked at the different tuning options when it comes to filesystems. Filesystems offer different mount options that can be changed to reduce some I/O overhead. Additionally, the filesystem block size, its geometry, and I/O alignment in terms of the underlying RAID configuration can also impact performance. Finally, we explained some use cases of the different scheduling flavors in Linux.
I guess that’s a wrap! I sincerely hope that this book took you on an enlightening exploration of the intricate layers comprising the Linux kernel’s storage stack. Starting with an introduction to VFS in Chapter 1, we tried to navigate the complex terrain of storage architecture. Each chapter delves deeper into the intricacies of the Linux storage stack, exploring topics such as VFS data structures, filesystems, the role of the block layer, multi-queue and device-mapper frameworks, I/O scheduling, the SCSI subsystem, physical storage hardware, and its performance tuning and analysis. Our goal was to prioritize the conceptual side of things and examine the flow of disk I/O activity, which is why we’ve not dived too much into general storage administration tasks.
As we bring our adventure to a close, I hope you’ve gained a comprehensive understanding of the Linux storage stack, its major components, and their interactions, and now possess the necessary knowledge and skills to make informed decisions, analyze, troubleshoot, and optimize storage performance in Linux environments.