Copy on Write

Well I suppose it had to happen. Someone in the office asked me what was Copy on Write(aka COW) and what was the point of it.
To put it succinctly, Copy on Write is where you share a page until some destructive activity is performed on it, whereupon the writing process is given a new private copy (well duh!) of the page which is no longer set to copy-on-write, all the other processes that are sharing the page keep the shared, unchanged page themselves.
Implementations of copy on write typically mark a page as un-writeable, and when the page is written to it causes an access fault. Because the page is marked as a COW page the OS knows to deal with it differently than an ordinary access fault. It creates a new page that contains the content of the old page, removes the COW bit from this page and marks it read/writeable then returns control to the process at the same address that caused the access fault. This causes the code to execute this instruction again, writing the data to this new private copy. If it didn't do this then you would not have the correct data in this location in only the new copy.
Why do we do this? It's quite simple really - forking. Every time you fork it needs to duplicate the address space of the parent process in the child. If you made a complete copy of all the data pages every time you forked this would amount to a large amount of memory that has to be kept around just to deal with memory that may or may not be used in the sub-process. If you consider that a whole truck load of forks are simply just to perform an exec of a new process the creation and teardown of the data is an horrible waste of processor time and resources so we don't do this.
This leads to an interesting problem. If you have, say 50 processes, each with a 1M COW segment you need to ensure that you have 50M of available swap just in case. Ever wonder what the difference between the allocated and reserved swap was? These COW pages are just another part of this equation.
Comments:

Post a Comment:
Comments are closed for this entry.
About

petesh

Search

Archives
« April 2014
MonTueWedThuFriSatSun
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
    
       
Today