How does OS manage memory and virtual memory?

This blog focuses on how operating system memory manages processes and Memory. Along with Memory allocation with fragmentation(Paging and segmentation). And, a little introduction to virtual memory in operating systems.

Program must be brought (from disk) into memory and placed within a process for it to be run.

  1. Main memory and registers are only storage CPU can access directly.
  2. Register access in one CPU clock (or less).
  3. Main memory can take many cycles.
  4. Cache sits between main memory and CPU registers.

In a multi-programming system, in order to share the processor, a number of processes must be kept in memory. 

Memory shared by Processes?

Each process has a separate memory space. The BASE register holds the smallest legal physical memory address; the LIMIT register specifies the size of the range.

The base and limit registers can be loaded only by the operating system. And these instructions can only be executed in kernel mode, which can only achieved by OS.

Different names in bonding,

  1. Symbolic Names: known in a context or path
    • file names, program names, printer/device names, user names
  2. Logical Names: used to label a specific entity
    • nodes, job number, major/minor device numbers, process id (pid), uid, gid..
  3. Physical Names: address of an entity
    • node address on disk or memory
    • entry point or variable address
    • PCB address

Binding of Instructions and Data to Memory,

  1. Compile time: If memory location known a priori, absolute code can be generated; must recompile code if starting location changes.
  2. Load time: Must generate relocatable code if memory location is not known at compile time
  3. Execution time: Binding delayed until run time if the process can be moved during its execution from one memory segment to another. 

Logical vs. Physical Address Space?

When running a user program, the CPU deals with logical addresses. The memory controller sees a stream of physical addresses.

  1. Logical address–generated by the CPU; also referred to as virtual address.
  2. Physical address– address seen by the memory unit.

Logical and physical addresses are the same in compile-time and load-time address-binding schemes; logical and physical addresses differ in an execution-time address-binding scheme.

Memory-Management Unit (MMU) :

The run time mapping from virtual to physical address is done by a hardware device called the memory-management unit, as well as MMU.

  1. In MMU scheme, the value in the relocation register (base register) is added to every address generated by a user process at the time it is sent to memory
  2. The user program deals with logical addresses; it never sees the real physical addresses.
Credits:http://users.cs.cf.ac.uk/O.F.Rana/os/lectureos8/img7.gif

Dynamic Loading: If the entire program and all data must be in physical memory for the process to execute, the size of the process is limited to the size of physical memory.

  1. To obtain better memory-space utilization, we can use dynamic loading.
  2. Useful when large amounts of code are needed to handle infrequently occurring cases.
  3. No special support from the operating system is required implemented through program design.

Dynamic Linking: Linking postponed until execution time.

  1. Small piece of code, stub, used to locate the appropriate memory-resident library routine.
  2. Stub replaces itself with the address of the routine, and executes the routine.
  3. Operating system needed to check if routine is in processes’ memory address.
  4. Dynamic linking is particularly useful for libraries.
  5. System also known as shared libraries.
Swapping Processes? 

A process can swapped temporarily out of memory to a Backing store and then brought back into memory for continued execution. Some of the components used are,

It must be large enough to store all memory images for all users, and it must have a direct access to memory.

  1. Backing Store – fast disk large enough to accommodate copies of all memory images for all users; must provide direct access to these memory images.
  2. Roll out, roll in – swapping variant used for priority based scheduling algorithms; lower priority process is swapped out, so higher priority process can be loaded and executed.
  3. Major part of swap time is transfer time; total transfer time is directly proportional to the amount of memory swapped.

Whenever the CPU scheduler decides to execute a process, it calls the dispatcher. The dispatcher will check whether the next process is in the memory. If not, the dispatcher will swap out a process currently in memory and swaps in the desired process.

Memory Allocation:

The simplest method for memory allocation is to divide memory into several fix-sized partitions. Initially, all memory is available for user processes and is considered one large block of available memory, a hole. 

Resident operating system, usually held in low memory with interrupt vector and user processes are held in high memory.

Single partition allocation

  1. MMU maps logical addresses dynamically.
  2. Relocation register scheme used to protect user processes from each other, and from changing OS code and data.
  3. Relocation register contains value of smallest physical address; limit register contains range of logical addresses – each logical address must be less than the limit register.

Dynamic storage allocation problem

When a process arrives and needs memory, the system searches the set for a hole that is large enough for it.

  1. If it is too large, the space divided into two parts. One part is allocate for the process and another part is freed to the set of holes.
  2. When the process terminate, the space is placed back in the set of holes.
  3. If the space is not big enough, the process wait or next available process comes in.

How to satisfy a request of size n from a list of free holes?

  • First-fit: Allocate the first hole that is big enough.
  • Best-fit: Allocate the smallest hole that is big enough; must search entire list, unless ordered by size (Produces the smallest leftover hole).
  • Worst-fit: Allocate the largest hole; must also search entire list (Produces the largest leftover hole).

Fragmentation:

All strategies for memory allocation suffer from external fragmentation.

  • external fragmentation: as process are loaded and removed from memory, the free memory space is broken into little pieces.
  • External fragmentation exists when there is enough total memory space to satisfy the request, but available spaces are not contiguous

If we use fixed partition scheme then we may have internal fragmentation.

  • If the hole is the size of 20,000 bytes, suppose that next process requests 19,000 bytes.  1,000 bytes are lost.
  • This is called internal fragmentation- memory that is internal to a partition but is nor being used.
Credits: https://lh6.googleusercontent.com/j7hCw84mnvhe-szSj9Lgvg8kEPTuzuYoK4dKZu227c3OpdQ6JFmax3t7kBnThgdbUfEubPep8t3MRCaTRiTvYDxuC0BMFbbhJtg4gz5PuDUpb-ZQ1qPtTqa3qBhbNgB0w1kIda5p

Internal Fragmentation happens in Fixed sized allocation and External Fragmentation happens in Variable sized allocation.

Possible solution to external fragmentation problem is to permit the logical address space of the process to be non contiguous. Thus, allowing a process to be allocated physical memory wherever the space is available. Two complementary techniques achieves this solution: paging and segmentation.

A.Paging

Paging is a memory-management scheme that permits the physical address space of a process to be non-contiguous.

  1. The basic method for implementation involves breaking physical memory into fixed-sized blocks called FRAMES and break logical memory into blocks of the same size called PAGES.
    • Frames = physical blocks
    • Pages = logical blocks
    • Size of frames/pages is defined by hardware (power of 2 to ease calculations

Every address generated by the CPU is divided into two parts: Page number (p) and Page offset (d). The page number is used as an index into a Page Table and page offset is used to find data in exact Page Table.

Advantages of big pages:

  1. Page table size is smaller
  2. Frame allocation accounting is simpler

Advantages of small pages:

  1. Internal fragmentation is reduced

When we use a paging scheme, we have no external fragmentation: ANY free frame can be allocated to a process that needs it. However, we may have internal fragmentation. If the process requires n pages, at least n frames are required.

The first page of the process is loaded into the first frame listed on free-frame list, and the frame number is put into page table. The Process loading procedure is,

  1. Split process logical address space into pages.
  2. Find enough free frames for the process’ pages.
  3. If necessary, swap out an old process.
  4. Find a sufficient number of free frames.
  5. Copy process pages into their designated frames.
  6. Fill in the page table.
Hardware Support on Paging

A standard solution is to use a special, small, fast cache, called Translation look-aside buffer (TLB) or associative memory.

If the page number is not in the TLB (TLB miss) a memory reference to the page table must be made.   In addition, we add the page number and frame number into TLB. If the TLB already full, the OS have to must select one for replacement

Some TLBs allow entries to be wire down, meaning that they cannot be removed from the TLB, for example kernel codes. The percentage of times that a particular page number is found in the TLB is called hit ratio.

Memory Protection?

Memory protection implemented by associating protection bit with each frame. Valid-invalid bit attached to each entry in the page table:

  1. “valid” indicates that the associated page is in the process’s logical address space, and is thus a legal page.
  2. “invalid” indicates that the page is not in the process logical address space.
Structure of the Page Table

Shared Pages : An advantage of paging is the possible of sharing common code, especially time-sharing environment.

1.Hierarchical Paging: Break up the logical address space into multiple page tables. A simple technique is a two-level page table.

A logical address (on 32-bit machine with 1K page size) is divided into:

  1. a page number consisting of 22 bits
  2. a page offset consisting of 10 bits

Since the page table is paged, the page number is further divided into:

  1. a 12-bit page number 
  2. a 10-bit page offset

Thus, a logical address is as follows:

where pi is an index into the outer page table, and p2 is the displacement within the page of the outer page table

2.Hashed Page Tables: The virtual page number is hashed into a page table.

This page table contains a chain of elements hashing to the same location. The virtual page number is hashed into a page table. This page table contains a chain of elements hashing to the same location

Common in address spaces > 32 bits

Each element contains (1) the virtual page number (2) the value of the mapped page frame (3) a pointer to the next element

  1. Virtual page numbers are compared in this chain searching for a match
  2. If a match is found, the corresponding physical frame is extracted
  3. Variation for 64-bit addresses is clustered page tables
  4. Especially useful for sparse address spaces (where memory references are non-contiguous and scattered) 

3.Inverted Page Tables: One entry for each real page of memory

Entry consists of the virtual address of the page stored in that real memory location, with information about the process that owns that page

  1. Decreases memory needed to store each page table, but increases time needed to search the table when a page reference occurs.
  2. Use hash table to limit the search to one — or at most a few — page-table entries

Rather than each process having a page table and keeping track of all possible logical pages, track all physical pages. One entry for each real page of memory

B.Segmentation:

Memory-management scheme that supports user view of memory. A program is a collection of segments

A segment is a logical unit such as: main program procedure function method object local variables, global variables common block stack symbol table  arrays

Segmentation Architecture 

Logical address consists of a two tuple:  <segment-number, offset>,

  1. Segment table – maps two-dimensional physical addresses; each table entry has:
    • base – contains the starting physical address where the segments reside in memory
    • limit – specifies the length of the segment
  2. Segment-table base register (STBR) points to the segment table’s location in memory
  3. Segment-table length register (STLR) indicates number of segments used by a program;

                      segment number s is legal if s < STLR

Protection

Protection bits associated with segments; code sharing occurs at segment level

Since segments vary in length, memory allocation is a dynamic storage-allocation problem

  1. With each entry in segment table associate:
    • validation bit = 0 ⇒ illegal segment
    • read/write/execute privileges

Virtual Memory

Virtual memory is a technique that allows the execution of processes which are not completely available in memory. The main visible advantage of this scheme is that programs can be larger than physical memory. Virtual memory is the separation of user logical memory from physical memory. 

This separation allows an extremely large virtual memory to be provided for programmers when only a smaller physical memory is available. Following are the situations, when entire program is not required to be loaded fully in main memory.

User written error handling routines are used only when an error occurred in the data or computation. Certain options and features of a program may be used rarely.

Many tables are assigned a fixed amount of address space even though only a small amount of the table is actually used. The ability to execute a program that is only partially in memory would counter many benefits.

  1. Less number of I/O would be needed to load or swap each user program into memory.
  2. A program would no longer be constrained by the amount of physical memory that is available.
  3. Each user program could take less physical memory, more programs could be run the same time, with a corresponding increase in CPU utilization and throughput.

Virtual address space – logical view of how process is stored in memory

Usually start at address 0, contiguous addresses until end of space. Meanwhile, physical memory organized in page frames, MMU must map logical to physical.

Usually design logical address space for stack to start at Max logical address and grow “down” while heap grows “up”

  1. Maximizes address space use
  2. Unused address space between the two is hole
    • No physical memory needed until heap or stack grows to a given new page

Virtual memory can be implemented via:

  1. Demand paging 
  2. Demand segmentation

A.Demand Paging: Could bring entire process into memory at load time or bring a page into memory only when it is needed

  1. Less I/O needed, no unnecessary I/O
  2. Less memory needed 
  3. Faster response
  4. More users
  1. Page is needed ⇒ reference to it
    • invalid reference ⇒ abort
    • not-in-memory ⇒ bring to memory

Lazy swapper – never swaps a page into memory unless page will be needed. So, swapper that deals with pages is a pager

Page Fault?

If there is a reference to a page, first reference to that page will trap to operating system:

  1. Operating system looks at another table to decide:
    • Invalid reference ⇒ abort
    • Just not in memory
  2. Find free frame
  3. Swap page into frame via scheduled disk operation
  4. Reset tables to indicate page now in memory
    Set validation bit = v
  5. Restart the instruction that caused the page fault

Aspects of Demand Paging

  1. Actually, a given instruction could access multiple pages -> multiple page faults
    • Consider fetch and decode of instruction which adds 2 numbers from memory and stores result back to memory
    • Pain decreased because of locality of reference
  2. Hardware support needed for demand paging
    • Page table with valid / invalid bit
    • Secondary memory (swap device with swap space)
    • Instruction restart

Copy-on-Write (COW) allows both parent and child processes to initially share the same pages in memory.

If either process modifies a shared page, only then is the page copied. COW allows more efficient process creation as only modified pages are copied. In general, free pages are allocated from a pool of zero-fill-on-demand pages

  1. Pool should always have free frames for fast demand page execution
  2. vfork() variation on fork() system call has parent suspend and child using copy-on-write address space of parent
    • Designed to have child call exec()
    • Very efficient

What Happens if There is no Free Frame?

Used up by process pages

  1. Page replacement – find some page in memory, but not really in use, page it out
    • Algorithm – terminate? swap out? replace the page?
    • Performance – want an algorithm which will result in minimum number of page faults
  2. Same page may be brought into memory several times

Basic Page Replacement

Find the location of the desired page on disk and then find a free frame:

  1. If there is a free frame, use it
  2. If there is no free frame, use a page replacement algorithm to select a victim frame
  3. Write victim frame to disk if dirty

Bring  the desired page into the (newly) free frame; update the page and frame tables and continue the process by restarting the instruction that caused the trap.

Note now potentially 2 page transfers for page fault – increasing EAT

Page Replacement Algorithms

  1. First In First Out
  2. Least Recently Used
  3. Optimal Algorithm: Replace page that will not be used for longest period of time.
Credits: https://i.stack.imgur.com/v5awk.png
Thrashing?

A process is busy swapping pages in and out. If a process does not have “enough” pages, the page-fault rate is very high

  1. Page fault to get page
  2. Replace existing frame
  3. But quickly need replaced frame back
  4. This leads to:
    • Low CPU utilization
    • Operating system thinking that it needs to increase the degree of multiprogramming
    • Another process added to the system

Thrashing Prevention

  1. If one process starts thrashing, it cannot steal pages from another process and cause latter to thrash also.
  2. Working Set model method
    • Locality model
    • Process migrates from one locality to another
    • Localities may overlap
For more information on Operating systems,
  1. https://www.cs.uic.edu/~jbell/CourseNotes/OperatingSystems/
  2. cis2.oc.ctc.edu/oc_apps/Westlund/xbook/xbook.php?unit=01&proc=book

One thought on “How does OS manage memory and virtual memory?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s