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 kernel. This is a continuation of that where we look at the fork() system call and how it uses copy-on-write behind the scenes.
Following is a timestamped list of chapters in the video to help you navigate quickly. Also, I recommend watching the video at a higher speed to get a better experience.
* (00:00) Introduction: Copy-on-write with fork() and the Instagram example.
* (02:54) Copy-on-write recap: Sharing physical frames and making private copies when a process writes.
* (10:08) What fork() does: Creating a child process and inheriting the parent’s state.
* (13:15) A code example: Return values, inherited memory, and independent writes in parent and child.
* (18:26) Why use copy-on-write?: The cost of copying the parent’s memory.
* (21:05) Page tables after fork(): How parent and child initially share physical frames.
* (23:45) The shell and exec(): Why copying memory upfront would often be wasted work.
* (26:04) Handling a write: Read-only page-table entries, page faults, VMA permissions, and copying a frame.
* (30:01) Benefits and tradeoffs: Memory savings and the performance cost of deferred copying.
* (41:14) Python objects and reference counting: Why an expression like if x is None can cause memory writes.
* (45:16) Inside the interpreter: How evaluating an expression changes reference counts.
* (48:12) Immortal objects: Avoiding reference-count updates for objects that live throughout the runtime.
* (50:19) Wrap-up: Plans for a hands-on demonstration using Linux memory debugging tools.
If you are new to this series, it is based on my ebook called “Virtual Memory from First Principles”. It is available to read for free online and also available to purchase from Gumroad (PDF/Epub) and Amazon (Kindle edition).
And, if you want to watch the previous videos in this series, the following is what has been published so far:
* 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
* Demand paging
* Demand Paging in Action: mmap, Page Faults, and RSS
* How Copy-on-Write Works with Memory-Mapped Files
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_01Hey everyone, this is Abhinav. Welcome back to our series on virtual memory. In the last video, we started to talk about copy and write and in that video, I also mentioned that this is such a wide topic that we will need at least two videos to cover it in its entirety.
SPEAKER_00So in the last video, we focused
SPEAKER_01on what copy and write is and then we took the example of the mmap system call and we Understood in depth how copy and write works right from the user space port where we are mapping a file right inside the kernel and at the hardware level when file data is actually accessed. And we also analyze what are the pros and cons of having copy and write.
SPEAKER_01And this video is a continuation of that. So in this video, we will focus on the fork system call, which is the second pathway where copy on write happens. And again, just like mMap, this is another area where copy on write happens behind the scenes. So it is not something we are deliberately enabling or asking the kernel to do. The kernel just uses copy and write automatically. And the same mechanics apply just like MMAP, but it's just a very different pathway.
SPEAKER_01So this video will focus on that. So we'll discuss why copy-on-write is actually needed when you use 4. And we will discuss the mechanics of copy-on-write on this pathway. And towards the end, we will also discuss a very interesting... Real world war story from Instagram because Instagram actually uses copy and write as a way to optimize their memory usage in their production systems. And they found a bug.
SPEAKER_01Where copy and write was actually working against their expectations, which then they had to debug and understand what was happening and what was causing that. So we'll discuss that. I think that story would make a lot of sense if you understand copy and write. And this is the reason that I want to talk about that story is because... In our systems as well, so whatever kind of systems that we are responsible for maintaining in our day jobs,
SPEAKER_01this kind of behavior, these kind of bugs can also show up. And without having a deep understanding of the mechanics of these kind of features, it can be very difficult to debug these kind of problems. So I think it would be very beneficial if you watch it till that point of time. So, let's start this video with a quick recap of copy and write and then from there,
SPEAKER_00we'll go towards fourth.
SPEAKER_01So, let's start with a recap. So, we know that the memory of a process has two aspects. Whenever we are talking about the memory of a process, there are two parts to it. One is the virtual memory and the other is the real physical memory where the real data is actually stored. So, the virtual memory It consists of virtual pages. Each page is usually 4KB in size. And a virtual page is mapped to a physical frame, which is also 4KB.
SPEAKER_014KB is not something hard-coded or, you know, It depends on the kernel and the hardware architecture. So I'm using 4KB because for a very long time, it has been the standard everywhere. Most operating systems and most hardware have been using 4KB for a very long time. But now slowly, things are changing. But on x86, on Linux kernel, 4KB is still the default. So virtual page of 4KB. Is mapped to a physical frame of 4KB.
SPEAKER_01The real data is stored in the physical frame, but in the processes machine code, all the instructions actually use virtual addresses. So whenever the hardware, whenever in our code, we are doing any memory access, the hardware has to translate the virtual address to a physical address and it has to figure out the translation. So this mapping of virtual to physical pages, And this is where it comes into the picture. So this mapping is maintained by a kernel in a structure called a page table.
SPEAKER_01We have talked about page table in a past video. So I recommend that you go and watch that. So I assume all of us are experts in virtual tables at this point of time. I'll just draw a simplistic picture to depict it. So let's say this is the page table of a process. In reality, a page table is a multi-level structure, but here I am just drawing the final level, let's say. Make it a bit smaller.
SPEAKER_01Okay, so let's say this is the page table of a process. These rows that we are seeing are virtual pages.
SPEAKER_00And then let's also draw the physical memory. So again, I'll draw a box here.
SPEAKER_01And the physical memory is similarly organized by the kernel in the form of frames, physical frames, each 4KB in this case. And these virtual pages are mapped to these frames. Let's say these two pages are mapped at this point of time.
SPEAKER_00Now, let's say there is another process. So, if we draw each space table. And let's say this for processes
SPEAKER_01page or one of its pages, virtual pages, is mapped to this frame. So now you can see that two processes are actually sharing this frame. So this sharing of frames, this sharing of physical frames in the RAM becomes possible due to
SPEAKER_00copy and write. So because...
SPEAKER_01So, if copy and write did not exist, this kind of sharing would be very difficult to maintain for the kernel. Because what if one of these processes wants to modify or write to this data? So, in that case, if the first process wants to write and if its write happens, then the second process would be reading data. The wrong data because one processes rights are private because
SPEAKER_01the process execution model is that every process executes in isolation. So it executes as if it is the only process running on the system. But in reality, there can be hundreds and thousands of processes running in parallel or conflict. So, if one process is reading or writing its own data, it is under the assumption that no one else is actually reading or writing the same, you know, or looking at that data at the same time. So, this kind of sharing would not be possible without copy and write.
SPEAKER_01So, now, how does copy and write actually enable this kind of sharing? So, what a kernel does is, whenever this kind of sharing happens, so these base table Entries are actually made either, so the kernel usually makes these pasteable entries as read-only. So, which means that any write from one of these processes is actually not going to go through. If any of these processes wants to do a write, the hardware will refuse to do the write because the pasteable entry says it's
SPEAKER_01a read-only page. But it could raise a page fault and a page fault is handled by the kernel. And when the kernel is handling the page fault, it realizes this is copy on write. So it makes a copy of this shared frame, which is why it's called a copy on write. So make a copy on a write. So now it has made a copy and whichever process wanted to do this right, now it updates its paste table to point to this new file. Copy of the frame. And now the pasteable entry,
SPEAKER_01it also updates the pasteable entry and makes it, you know, writable. So it removes the read-only restriction. So now if the first process wants to do a write, its write will go to this frame, which is a copy. And the second process continues to read the original frame. So that's how copy and write enables sharing of this data in the RAM between multiple processes. And in the last video, we used the example of the mmap system call because that's a very natural use case
SPEAKER_01of copy and write. Because many times, multiple processes are working with the same file. So if that file's data was being copied in the RAM for every process itself, That wanted to read or work with that file, then it would be a very inefficient utilization of the RAM, which is a very limited resource. But if copy and write is there, then the kernel can easily share those frames which contain file data
SPEAKER_01between those processes. And again, the same restrictions apply. These processes can share as long as they are reading the data rather than writing to it. Whenever they have to write, then A lot of, then the kernel has to step in and do a copy and write. So we discussed all of that in the last video. In this video, we will instead focus on the fork pathway, which is slightly different from the M-map pathway. So some differences will be there, which is why I wanted to make this video. So let's start from fork, what fork is.
SPEAKER_01So fork is a system call which exists on all Unix-like operating systems. It is used for creating a new process. So because it is a system call, it can be called only by another process. So if a process is executing, then that process can call fork. So, the process that is calling or executing fork system call is called a parent process. So, because this is the process that is actually creating a new process, it becomes a parent.
SPEAKER_01And process that gets created as a result of fork is called the child process. And it's a child of the parent, the parent process. And another reason for calling these as parent and child processes is that because the child process is almost a replica of the parent. So what do I mean by that? So the child process inherits the parent's file descriptor table. So if the parent process had opened a It had opened a few sockets.
SPEAKER_01Then the child process also inherits those. It gets a copy of the same file descriptor table. And similarly, it also receives a copy of the parents' virtual addresses page. What's the state of the parent's virtual address space? That state, same state has to be copied for the child process as well.
SPEAKER_01So, the child executes almost as if it was the same process. It almost is executing like that. So, when the fork system call returns back, the child starts executing right from the point after the fork system call. So, if the parent had allocated some memory, created a few variables, the child also will get the same state. Which is why the parent's virtual address space also has to be copied for the child.
SPEAKER_01So, that's another thing. Which, again, makes the child a copy of the parent. And finally, whatever... Data that the parent process had actually in the RAM, the child process also needs to have the same data because the child will execute as if it is the parent process, as if it is the same process. So, if the parent had, let's say, created an array and populated it with some data,
SPEAKER_01then the child process should also be able to work with the same data. But it will be a copy, not the same data because these are two independent processes. So, whatever the parent does with its own data should not be visible to the child. These are two independent processes, but the child is a copy of the parent. So, that's why. So, if I try to give an example, you know, in the form
SPEAKER_00of code. So, it would be like this. So, let's say, in my parent process, let's say, I did something like this. Let's say I allocated some memory using malloc. And let's say I opened a file using open.
SPEAKER_01And I'm not writing all the code here. But let's say I did a few things here. I allocated some memory using malloc. I opened a file. And let's say I also write some data into this array.
SPEAKER_00So let's say I write the value 42 into the first byte of that array. So let's say I've done all of this. And then after that, I call fault. And now fork returns the process ID of the child process. But it depends.
SPEAKER_01It actually has two written values. I mean, it depends whether it is returning to the parent process or is it returning to the child. Basically, fork is a single entry into the kernel and it has two return pathways back to the user space. So one return is to the parent process, which continues executing right after 4. And the other return is back to the child process, which also starts executing right after 4. So here we call 4.
SPEAKER_01Now it will return to the parent and the child process. So how do you distinguish is through the PID itself, the PID
SPEAKER_00value, the return value. So, in the child process, the PID value is 0. So, this becomes a child process. And here you can do whatever you want to do.
SPEAKER_01This will be... This is... The child processes context. So here, for example, I can still access everything. So here I can call close on FD1. So you can see that even though the child process did not open this file, but it can actually, it will still inherit the same file descriptor table. So which means the FD1 variable, whatever value it holds, points to the same file, but it is a different, its own file descriptor table.
SPEAKER_01It can also read and write that array. So it can modify this or
SPEAKER_00you can do assert or something.
SPEAKER_01This will also work because at this point of time, before fork was called, the parent had allocated some memory and the child process has to inherit or get a copy of the same address space. So whatever... Was the virtual address where this memory was allocated, the same address will be, the child will also get this pointer allocated at the same address. And whatever was the value at that address in the physical memory,
SPEAKER_01the child will also get a copy of that. So, that is why. So, I mean, the child simply should be able to continue executing as if, just like the parent.
SPEAKER_00So, which is why all of this has to happen or should be possible. Anyway, after and the else block is where the parent's code resumes.
SPEAKER_01So, basically in the parent, the PID variable would hold the child's process ID. So, if the PID value is non-zero, it means we are in the parent process. So, here anyway, we can do... You know, whatever we want to do. So here also we can continue to do, for example,
SPEAKER_00I can do this. So here, if the
SPEAKER_01parent goes and modifies this first byte and updates it to 84, it does not mean that the child processes assert would fail because child process has received a copy of this data rather than sharing that with the parent. So, if the parent modifies it, it does not mean that the parent or the child will read the updated value. The child will still see 42 at that address in the RAM.
SPEAKER_01So, that's the story of Ford. So, in theory, the child process
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 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...
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...