Let us talk about an important topic in linux called as Page Caching.

What is a Page in linux ?
A page is a fixed block of physical memory that the kernel uses to manage various operations. The typical size of a page in linux is around 4KB. It allows for efficient use of physical memory by sharing it among multiple processes and by swapping unused pages to disk when memory becomes scarce.

How is a page cache and how is read and write to a page cache done?
A page cache is linux’s way of accessing memory quicker. Generally if a the kernel wants to read a file it first checks if that file has its data in the page cache. If yes it can avoid the expensive operation of reading that data from disk.

How reads are done to the disk

  • When a user-space application wants to read data from disks, it asks the kernel for data using special system calls such as read(), pread(), vread(), mmap(), sendfile(), etc.

  • Linux kernel, in turn, checks whether the pages are present in Page Cache and immediately returns them to the caller if so. As you can see kernel has made 0 disk operations in this case.

  • If there are no such pages in Page Cache, the kernel must load them from disks. In order to do that, it has to find a place in Page Cache for the requested pages. A memory reclaim process must be performed if there is no free memory (in the caller’s cgroup or system).

How writes are done to the disk

It is the same as how reads are done but the only difference is the writes are not written immediately to disk. What this means is that the pages are just written to and are kept that way until a page flush occurs. The data that is not yet flushed is marked by the kernel as dirty pages.

This post was first published on Substack.

View the original