This is a free preview of a paid episode. To hear more, visit blog.codingconfessions.com Welcome back to the video series on virtual memory based on my article on the same topic. It is also available in ebook format on Gumroad (pdf/epub) and Amazon Kindle, if you prefer those formats. So far in this video series we have covered the foundational pieces behind virtual memory: * What is virtual memory and why do we need it * Size of the virtual address space of a process * Address space of a process * Structure of page tables and how page table walks work * What is inside a page table entry * Size of a physical address From here on, the next set of topics is going to be more advanced and important for debugging memory issues in real-world systems. The topic of this video is demand paging, which is central to how memory allocation works inside the kernel. Demand paging simply means that when you ask the kernel for more memory, it reserves a virtual address range for you but does not perform physical memory allocation until you actually need it. This can lead to tricky situations and unpredictable system performance if you do not design your systems keeping this in mind. The famous OOM killer that appears and kills your processes is also a result of demand paging, because the kernel may end up overcommitting more memory than what is physically available, and ultimately it has to kill a process to free up some memory to recover the system. In this 45-minute video, we cover in depth what demand paging is, what its benefits are, and how it works inside the Linux kernel. And if you watch the full video, you would also get an idea of how the kernel handles page faults for various situations, such as when the page has been swapped, illegal address access, accessing file-backed pages, accessing an unmapped, copy-on-write fault, etc. In the next follow-up video, I plan to do a hands-on demo of demand paging in action. We will use mmap and inspect the virtual memory of the process to see that merely calling mmap does not cause a physical page allocation, but accessing a page does. Wait for the next video!
Audio and video play straight from the show's own hosting. PodSubs stores and serves no media.
Transcript
From the show. Tap a time to play from there.
SPEAKER_00Hey everyone, this is Abhinav.
SPEAKER_01Welcome back to our series on virtual memory. So in this video, we are going to talk about demand paging. So in the previous set of videos, we have discussed the more foundational ideas behind virtual memory. So what is virtual memory? How it works? How address translation works? How a page table is structured? How a page table walk works? And the hardware side details, so things like TLB and page fault and all those things we have talked about.
SPEAKER_01So from here on, the next set of topics that we are going to discuss are going to be more interesting because they are strongly correlated to the behaviors of modern day systems. So any system that you either use or operate or build or design, they sort of build on top of... So, when you have memory pressure on your system and it starts behaving weirdly
SPEAKER_01and you are trying to investigate, then understanding how things like demand paging work becomes important. So... So I think from here on, you will find these topics much more relevant. So in this video, we're going to talk about demand paging. So we'll start by understanding what is demand paging, why is it needed, and finally, we will end by discussing the internals of the Linux kernel and
SPEAKER_01the internal data structures that make demand paging possible. And understanding the internal data structure, is really important here because whenever you are trying to debug virtual memory issues, you have to understand what these data structures are and what they look like because the kernel really exposes them. So any tooling that you use, you should be able to understand all these details to be able to investigate it effectively.
SPEAKER_01So we'll cover that in this video. So let's start by understanding what is demand paging. So demand paging is a very simple idea. So it's lazy allocation of physical memory inside the kernel. So whenever you, in your application, you're trying to allocate memory. So for example, if you are calling malloc or mmap
SPEAKER_00in your code, so if for example, let's say, I could do, for example, I might call mmap with some parameters to allocate, let's say,
SPEAKER_014096 bytes, which is one virtual memory page. So if I call mmap like this, Abhinav is a system call. It has to go inside the kernel and we're asking the kernel to allocate 4096 bytes, which is one page. So kernel essentially reserves our virtual memory address range and just gives us back the starting of that address range. So for example, p might become Might hold the address that the kernel has given us.
SPEAKER_00So 0x, let's say some 4KB aligned value. I'm just using 4096 here.
SPEAKER_01But it has to be a page aligned address anyway. So a map will return us some virtual address. But this address... Or the page has not yet been mapped to real physical memory. So mmap just simply allocates some virtual address range and it returns immediately. So there is no physical memory allocation at this point of time. So this is the lazy allocation or demand paging. So when exactly the real physical allocation happens? So when you try to access this memory for the first time.
SPEAKER_01So let's say somewhere else down the line,
SPEAKER_00we are trying to do something like We are accessing the first byte of
SPEAKER_01this page that we just allocated. At this point of time, what could happen is that first the hardware will try to translate this virtual address to a physical address. So it will try to do that by first checking the TLB. So because this is a freshly allocated address and we have never accessed it, so TLB will not contain So TLB will give us a cache miss. When that happens, the hardware has to do a page table walk. So it will go and do a page table walk and try to translate this address.
SPEAKER_01Because this is a freshly allocated address and the kernel is lazy. So it has not yet mapped this address to a physical page. So page table would not contain any mapping. So the hardware will not find any translation in the page table as well. When that happens, The hardware does not know what to do next. So, it raises an exception, which in this case is called a page fault. A page fault exception is handled by the kernel.
SPEAKER_01So, the kernel has a specific handler. Which is, you could think of it like a special routine, which is called by the hardware. So the hardware calls the kernel's page fault handler. It passes the address which calls the page fault. And now the ball is in the kernel's code. So the kernel has to figure out why the page fault happened. If it is possible to handle it safely, then the kernel would handle it. If it was an illegal access, then the kernel will most likely kill the process by sending it
SPEAKER_01a segmentation fault signal. So that is how it works. So on the first call to MMAP, the kernel does not allocate physical memory. It reserves a virtual address range and returns back to user space. The real physical memory allocation happens when the first time you access that address. And at that point of time, page fault happens and then the kernel would happen. We'll allocate physical memory for that. And in this case, we just allocated one page and the first access that we did would have allocated
SPEAKER_01a physical memory for that page. It is also possible that you allocated 10 pages. So instead of 4096 bytes, you allocated 4096 times 10. So 10 virtual memory pages. In that case, every page gets allocated lazily. So for example, if we just access the first page, only the first page would get a And that particular page would get a physical page mapping. But the remaining nine pages would not yet be physically mapped.
SPEAKER_01So they will eventually get mapped one by one as and when we access those pages. So that's how demand paging works.
SPEAKER_00Now the next question is, why do we need demand paging or why does it exist? So there are, you know, Quite a few
SPEAKER_01reasons that we can think of. So one of those reasons is that physical memory allocation is an expensive task. So when you call mmap, for example, here when we called mmap and we asked for 4096 bytes of memory, if the kernel had to really allocate physical memory at this point of time, it has to do a search. So it has some sort of an internal data structure where it knows Which addresses or
SPEAKER_01which pages, which physical pages are mapped to this process or other processes and which pages or which address ranges are yet not mapped. So it has to go through that and find the best fit or whatever the algorithm is to find a free physical page and then allocate information. Into your virtual address space and then return. So mmap would become an expensive call. So that is one reason. If the kernel doesn't really have to allocate that physical memory,
SPEAKER_01then mmap becomes really quick. It just returns back. It just checks within your virtual address space which address is not yet mapped. It picks up the right address range, gives it back to you and it's done. So that's one reason that why Demand Paging exists. Apart from that, there are other reasons as well. So one is that the behavior of all the user space applications
SPEAKER_01and systems is also optimized towards demand paging in a way. So, for example, in order to allocate memory, you have to call mmap. And mmap is a system call. And system calls are expensive. So... You don't want to execute system calls too frequently, especially in a hot path. So you try to minimize them. So one way to minimize too many MMAP system calls would be to allocate a large chunk of memory in a single MMAP system call rather than allocating,
SPEAKER_01you know, or rather than calling MMAP multiple times. So, for example, if you needed 40 KB of memory, so you would You would want to do a single mmap call rather than making 10 mmap calls. So this is the way all real-world applications and libraries are written. Even the malloc library behaves the same way or it is implemented the same way. So it uses mmap under the hood. So it would call mmap to allocate large chunk of memory.
SPEAKER_01It might allocate 1mb, 2mb or 10mb, some large segment of memory using mmap. Whenever your application calls malloc, it will find one, you know, for example, if you call malloc for 10 KB of memory, so malloc would find within that large segment, where is that 10 KB free block that it can give back to your process. So that malloc doesn't have to go to the operating system every time it needs to allocate memory. So malloc is also doing the same thing.
SPEAKER_01So the kernel is basically optimizing for this behavior as well. So it knows that malloc may call mmap for a large chunk of memory, but malloc is not going to use all of that memory immediately. So there is no point doing physical memory allocation immediately. So that's why the operating system is also trying to be lazy in that sense. So it is trying to match what malloc and all the real world systems do. So that is another reason.
SPEAKER_01So if the operating system was not lazy, then if malloc asked for 10 MB of memory, then the operating system would have to allocate 10 MB of physical memory right at that point of time. So it would have two problems. One is that mmap would become really expensive or slow. And secondly, If 10MB was allocated, 10MB of physical memory was reserved for your process, then any other process now would not, you know, 10MB is simply gone from the system.
SPEAKER_01Now it is not available for any other process, even if your process is not really using that memory. But demand paging allows that. So demand paging essentially allows multiple processes to be able to execute simultaneously and allocate memory at the same time. Even if the amount of physical memory available on the system is limited. So even if you have 1 GB of RAM installed on your hardware, you may still execute several processes simultaneously and those processes may be allocating a lot of memory.
SPEAKER_01But because the operating system does not have to reserve all of that memory for all the processes at the same time, they can execute without slowing down the system. So the operating system cleverly manages the limited amount of memory by using page reclamation, swapping pages to the disk, swapping unused pages to the disk, and then allocating those physical pages to another process and so on. So in a way, it just works out. But if demand paging did not exist, then this would not be possible.
SPEAKER_01So if two processes simply allocated all the entire physical memory of your system, then the third process could not run at the same time. So basically, those are all the various reasons that you can think because of which demand paging exists. Now let's move towards how this really works inside the Linux kernel. So I'll be talking about the Linux kernel here because, I mean, but the ideas are very
SPEAKER_00similar in all operating system kernels. So, let's talk about, let's start by
SPEAKER_01revisiting how the virtual memory address space looks like. And from there, we will move towards how the kernel manages this
SPEAKER_00address space. So, on x86-64 platform, a processor's virtual address
SPEAKER_01space spans It has this linear virtual address space which goes from the virtual address 0 up to 2 to the power of 48. So, the virtual address size on x8664 is 48 bits. So, the maximum address range is from 0 to 2 to the power 48 minus 1. This is the address space range. But not, this is a huge address space.
SPEAKER_01This is like 256 terabytes of memory. But not all of that is actually mapped. Because most real-world systems don't simply have that much of physical memory anyway. So only what certain address ranges are mapped to physical memory and those are the addresses that you can actually access. So when your process is created, the operating system first allocates memory for certain address ranges in this.
SPEAKER_01So for example, it may map Certain address range for the text section. This text section is where all the executable code is loaded. And it is always towards the lower address ranges. So, towards the zero. It may not be exactly at zero, but somewhere near to zero. And it goes. So, depending on how much code So, for example, if the amount of executable code is,
SPEAKER_01let's say, 10 KB, so this text section may go from 0 to,
SPEAKER_00let's say, 10 times, let's say,
SPEAKER_0140 KB. If your program has 40 KB of code, then the text section may go from 0 to whatever is 10 times 4096. And then this section has some permissions. All the pages, this is 10 pages, all the pages would have the same permission. So they would be readable and they would be executable.
This is a free preview of a paid episode. To hear more, visit blog.codingconfessions.com In the last video, we learned about copy-on-write (CoW) and understood its mechanics by digging inside the mmap pathway in the...
This is a free preview of a paid episode. To hear more, visit blog.codingconfessions.com In the last video, we discussed demand paging. Now, let’s move towards an even more interesting topic: copy-on-write (CoW). Just...
This is a free preview of a paid episode. To hear more, visit blog.codingconfessions.com In the previous video in our virtual memory series, we discussed demand paging. But that was mostly theoretical, explaining how...
This is a free preview of a paid episode. To hear more, visit blog.codingconfessions.com This is a short aside in our virtual memory series. We have talked extensively about the size of a virtual address and the virtual...
This is a free preview of a paid episode. To hear more, visit blog.codingconfessions.com This is the 5th video in our virtual memory series. In the previous video, we learned about the page table and how the hardware...