The Wayback Machine - https://web.archive.org/web/20240926194407/https://www.geeksforgeeks.org/virtual-memory-in-operating-system/
Open In App

Virtual Memory in Operating System

Last Updated : 30 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Virtual Memory is a storage allocation scheme in which secondary memory can be addressed as though it were part of the main memory. The addresses a program may use to reference memory are distinguished from the addresses the memory system uses to identify physical storage sites and program-generated addresses are translated automatically to the corresponding machine addresses.

What is Virtual Memory?

Virtual memory is a memory management technique used by operating systems to give the appearance of a large, continuous block of memory to applications, even if the physical memory (RAM) is limited. It allows the system to compensate for physical memory shortages, enabling larger applications to run on systems with less RAM.

A memory hierarchy, consisting of a computer system’s memory and a disk, enables a process to operate with only some portions of its address space in memory. A virtual memory is what its name indicates- it is an illusion of a memory that is larger than the real memory. We refer to the software component of virtual memory as a virtual memory manager. The basis of virtual memory is the noncontiguous memory allocation model. The virtual memory manager removes some components from memory to make room for other components.

The size of virtual storage is limited by the addressing scheme of the computer system and the amount of secondary memory available not by the actual number of main storage locations. 

Working of Virtual Memory

It is a technique that is implemented using both hardware and software. It maps memory addresses used by a program, called virtual addresses, into physical addresses in computer memory. 

  • All memory references within a process are logical addresses that are dynamically translated into physical addresses at run time. This means that a process can be swapped in and out of the main memory such that it occupies different places in the main memory at different times during the course of execution.
  • A process may be broken into a number of pieces and these pieces need not be continuously located in the main memory during execution. The combination of dynamic run-time address translation and the use of a page or segment table permits this.

If these characteristics are present then, it is not necessary that all the pages or segments are present in the main memory during execution. This means that the required pages need to be loaded into memory whenever required. Virtual memory is implemented using Demand Paging or Demand Segmentation.

Types of Virtual Memory

In a computer, virtual memory is managed by the Memory Management Unit (MMU), which is often built into the CPU. The CPU generates virtual addresses that the MMU translates into physical addresses.

There are two main types of virtual memory:

Paging

Paging divides memory into small fixed-size blocks called pages. When the computer runs out of RAM, pages that aren’t currently in use are moved to the hard drive, into an area called a swap file. The swap file acts as an extension of RAM. When a page is needed again, it is swapped back into RAM, a process known as page swapping. This ensures that the operating system (OS) and applications have enough memory to run.

Demand Paging: The process of loading the page into memory on demand (whenever a page fault occurs) is known as demand paging. The process includes the following steps are as follows: 

Demand Paging

Demand Paging

  • If the CPU tries to refer to a page that is currently not available in the main memory, it generates an interrupt indicating a memory access fault.
  • The OS puts the interrupted process in a blocking state. For the execution to proceed the OS must bring the required page into the memory.
  • The OS will search for the required page in the logical address space.
  • The required page will be brought from logical address space to physical address space. The page replacement algorithms are used for the decision-making of replacing the page in physical address space.
  • The page table will be updated accordingly.
  • The signal will be sent to the CPU to continue the program execution and it will place the process back into the ready state.

Hence whenever a page fault occurs these steps are followed by the operating system and the required page is brought into memory. 

What is Page Fault Service Time?

The time taken to service the page fault is called page fault service time. The page fault service time includes the time taken to perform all the above six steps. 

Let Main memory access time is: m
Page fault service time is: s
Page fault rate is : p
Then, Effective memory access time = (p*s) + (1-p)*m

Segmentation

Segmentation divides virtual memory into segments of different sizes. Segments that aren’t currently needed can be moved to the hard drive. The system uses a segment table to keep track of each segment’s status, including whether it’s in memory, if it’s been modified, and its physical address. Segments are mapped into a process’s address space only when needed.

Combining Paging and Segmentation

Sometimes, both paging and segmentation are used together. In this case, memory is divided into pages, and segments are made up of multiple pages. The virtual address includes both a segment number and a page number.

Virtual Memory vs Physical Memory

When talking about the differences between virtual memory and physical memory, the biggest distinction is speed. RAM is much faster than virtual memory, but it is also more expensive.

When a computer needs storage for running programs, it uses RAM first. Virtual memory, which is slower, is used only when the RAM is full.

Feature Virtual Memory Physical Memory (RAM)
Definition An abstraction that extends the available memory by using disk storage The actual hardware (RAM) that stores data and instructions currently being used by the CPU
Location On the hard drive or SSD On the computer’s motherboard
Speed Slower (due to disk I/O operations) Faster (accessed directly by the CPU)
Capacity Larger, limited by disk space Smaller, limited by the amount of RAM installed
Cost Lower (cost of additional disk storage) Higher (cost of RAM modules)
Data Access Indirect (via paging and swapping) Direct (CPU can access data directly)
Volatility Non-volatile (data persists on disk) Volatile (data is lost when power is off)

What is Swapping?

Swapping is a process out means removing all of its pages from memory, or marking them so that they will be removed by the normal page replacement process. Suspending a process ensures that it is not runnable while it is swapped out. At some later time, the system swaps back the process from the secondary storage to the main memory. When a process is busy swapping pages in and out then this situation is called thrashing. 

Swapping

Swappinghierar

What is Thrashing?

At any given time, only a few pages of any process are in the main memory, and therefore more processes can be maintained in memory. Furthermore, time is saved because unused pages are not swapped in and out of memory. However, the OS must be clever about how it manages this scheme. In the steady state practically, all of the main memory will be occupied with process pages, so that the processor and OS have direct access to as many processes as possible. Thus when the OS brings one page in, it must throw another out. If it throws out a page just before it is used, then it will just have to get that page again almost immediately. Too much of this leads to a condition called Thrashing. The system spends most of its time swapping pages rather than executing instructions. So a good page replacement algorithm is required. 

In the given diagram, the initial degree of multiprogramming up to some extent of point(lambda), the CPU utilization is very high and the system resources are utilized 100%. But if we further increase the degree of multiprogramming the CPU utilization will drastically fall down and the system will spend more time only on the page replacement and the time taken to complete the execution of the process will increase. This situation in the system is called thrashing. 

Causes of Thrashing

Thrashing

1. High Degree of Multiprogramming: If the number of processes keeps on increasing in the memory then the number of frames allocated to each process will be decreased. So, fewer frames will be available for each process. Due to this, a page fault will occur more frequently and more CPU time will be wasted in just swapping in and out of pages and the utilization will keep on decreasing. 

For example: 
Let free frames = 400 
Case 1: Number of processes = 100 
Then, each process will get 4 frames. 

Case 2: Number of processes = 400 
Each process will get 1 frame. 
Case 2 is a condition of thrashing, as the number of processes is increased, frames per process are decreased. Hence CPU time will be consumed just by swapping pages. 

2. Lacks of Frames: If a process has fewer frames then fewer pages of that process will be able to reside in memory and hence more frequent swapping in and out will be required. This may lead to thrashing. Hence a sufficient amount of frames must be allocated to each process in order to prevent thrashing.

Recovery of Thrashing 

  • Do not allow the system to go into thrashing by instructing the long-term scheduler not to bring the processes into memory after the threshold.
  • If the system is already thrashing then instruct the mid-term scheduler to suspend some of the processes so that we can recover the system from thrashing.

Performance in Virtual Memory

  •  Let p be the page fault rate( 0 <= p <= 1).
  • if p = 0 no page faults
  • if p =1, every reference is a fault.
Effective access time (EAT) = (1-p)* Memory Access Time + p * Page fault time.
Page fault time = page fault overhead + swap out + swap in +restart overhead

The performance of a virtual memory management system depends on the total number of page faults, which depend on “paging policies” and “frame allocation“

Frame Allocation

    A number of frames allocated to each process in either static or dynamic.

  • Static Allocation: The number of frame allocations to a process is fixed.
  • Dynamic Allocation:  The number of frames allocated to a process changes.

Paging Policies

  • Fetch Policy: It decides when a page should be loaded into memory.
  • Replacement Policy: It decides which page in memory should be replaced.
  • Placement Policy: It decides where in memory should a page be loaded.

Applications of Virtual memory

Virtual memory has the following important characteristics that increase the capabilities of the computer system. The following are five significant characteristics of Lean.

  • Increased Effective Memory: One major practical application of virtual memory is, virtual memory enables a computer to have more memory than the physical memory using the disk space. This allows for the running of larger applications and numerous programs at one time while not necessarily needing an equivalent amount of DRAM.
  • Memory Isolation: Virtual memory allocates a unique address space to each process and that also plays a role in process segmentation. Such separation increases safety and reliability based on the fact that one process cannot interact with and or modify another’s memory space through a mistake, or even a deliberate act of vandalism.
  • Efficient Memory Management: Virtual memory also helps in better utilization of the physical memories through methods that include paging and segmentation. It can transfer some of the memory pages that are not frequently used to disk allowing RAM to be used by active processes when required in a way that assists in efficient use of memory as well as system performance.
  • Simplified Program Development: For case of programmers, they don’t have to consider physical memory available in a system in case of having virtual memory. They can program ‘as if’ there is one big block of memory and this makes the programming easier and more efficient in delivering more complex applications.

How to Manage Virtual Memory?

Here are 5 key points on how to manage virtual memory:

1. Adjust the Page File Size

  • Automatic Management: All contemporary operating systems including Windows contain the auto-configuration option for the size of the empirical page file. But depending on the size of the RAM, they are set automatically, although the user can manually adjust the page file size if required.
  • Manual Configuration: For tuned up users, the setting of the custom size can sometimes boost up the performance of the system. The initial size is usually advised to be set to the minimum value of 1. To set the size of the swap space equal to 5 times the amount of physical RAM and the maximum size 3 times the physical RAM.

2. Place the Page File on a Fast Drive

  • SSD Placement: If this is feasible, the page file should be stored in the SSD instead of the HDD as a storage device. It has better read and write times, and the virtual memory may prove benefecial in an SSD.
  • Separate Drive: Regarding systems having multiple drives involved, the page file needs to be placed on a different drive than the os and that shall in turn improve its performance.

3. Monitor and Optimize Usage

  • Performance Monitoring: Employ the software tools used in monitoring the performance of the system in tracking the amounts of virtual memory. High page file usage may signify that there is a lack of physical RAM or that virtual memory needs a change of settings or addition in physical RAM.
  • Regular Maintenance: Make sure there is no toolbar or other application running in the background, take time and uninstall all the tool bars to free virtual memory.

4. Disable Virtual Memory for SSDs (with Sufficient RAM)

  • Sufficient RAM: If for instance your system has a big physical memory, for example 16GB and above then it would be advised to freeze the page file in order to minimize SSD usage. But it should be done, in my opinion, carefully and only if the additional signals that one decides to feed into his applications should not likely use all the available RAM.

5. Optimize System Settings

  • System Configuration: Change some general properties of the system concerning virtual memory efficiency. This also involves enabling additional control options in Windows such as adjusting additional system setting option on the operating system, or using other options in different operating systems such as Linux that provides different tools and commands to help in adjusting how virtual memory is utilized.
  • Regular Updates: Ensure that your drivers are run in their newest version because new releases contain some enhancements and issues regarding memory management.

Advantages of Virtual Memory

  • More processes may be maintained in the main memory: Because we are going to load only some of the pages of any particular process, there is room for more processes. This leads to more efficient utilization of the processor because it is more likely that at least one of the more numerous processes will be in the ready state at any particular time.
  • A process may be larger than all of the main memory: One of the most fundamental restrictions in programming is lifted. A process larger than the main memory can be executed because of demand paging. The OS itself loads pages of a process in the main memory as required.
  • It allows greater multiprogramming levels by using less of the available (primary) memory for each process.
  • It has twice the capacity for addresses as main memory.
  • It makes it possible to run more applications at once.
  • Users are spared from having to add memory modules when RAM space runs out, and applications are liberated from shared memory management.
  • When only a portion of a program is required for execution, speed has increased.
  • Memory isolation has increased security.
  • It makes it possible for several larger applications to run at once.
  • Memory allocation is comparatively cheap.
  • It doesn’t require outside fragmentation.
  • It is efficient to manage logical partition workloads using the CPU.
  • Automatic data movement is possible.

Disadvantages of Virtual Memory

  • It can slow down the system performance, as data needs to be constantly transferred between the physical memory and the hard disk.
  • It can increase the risk of data loss or corruption, as data can be lost if the hard disk fails or if there is a power outage while data is being transferred to or from the hard disk.
  • It can increase the complexity of the memory management system, as the operating system needs to manage both physical and virtual memory.

Conclusion

In conclusion, virtual memory is a crucial feature in operating systems that allows computers to run larger applications and handle more processes than the physical RAM alone can support. By using techniques like paging and segmentation, the system extends the available memory onto the hard drive, ensuring that the operating system and applications can operate smoothly. Although virtual memory can introduce some performance overhead due to the slower speed of hard drives compared to RAM, it provides significant benefits in terms of memory management, efficiency, and multitasking capabilities.

Frequently Asked Questions on Virtual Memory – FAQs

Why is virtual memory important?

Virtual memory is important because it allows the system to handle larger applications and multiple applications simultaneously without running out of physical memory. It helps in optimizing the use of available RAM and provides a buffer against memory shortages.

What is a page file or swap space in virtual memory?

Page file is also known as Virtual memory file in windows while Swap space is known as page file in Unix/Linux It is a disk area assigned by the operating system to act as extension of physical memory. If RAM is saturated, then finally inactive page of memory is swapped to this area, to provide the occupied RAM for more active processes. This process is known as paging or swapping.

Can virtual memory affect system performance?

Virtual memory may affect the efficiency of the operation of the computer. Too much usage of the virtual memory will result in what is referred to as a thrashing where the system spends most of its time swapping data between the RAM and the disk with little time executing applications thus, slows down the system. This can be solved by having enough physical RAM and to correctly setup the page file or swap space.

What is a page fault?

A page fault occurs when a program tries to access data that is not currently in RAM. The operating system then retrieves the required page from the hard drive and loads it into RAM.



Previous Article
Next Article

Similar Reads

Difference between Virtual memory and Cache memory
Cache Memory: Cache memory increases the accessing speed of CPU. It is not a technique but a memory unit i.e a storage device. In cache memory, recently used data is copied. Whenever the program is ready to be executed, it is fetched from main memory and then copied to the cache memory. But, if its copy is already present in the cache memory then t
2 min read
Virtual Address Space in Operating System
In operating systems, Virtual memory plays a very vital role, in managing the memory allotted to different processes and efficiently isolating the different memory addresses. The role of the virtual address is to assign a space to the ledger of all the virtual memory areas that are provided to different processes. This process enables the process t
5 min read
Virtual Machines in Operating System
A Virtual Machine is an Operating System or application environment that runs on software that replicates special hardware. The end-user experience when utilizing a virtual machine is identical to that of special hardware. What is Virtual Machine?Virtual Machine abstracts the hardware of our personal computer such as CPU, disk drives, memory, NIC (
5 min read
Best Ways for Operating System Memory Management
Prerequisite - Partition Allocation Methods Contiguous Memory Allocation :Probably the least difficult technique for the memory portion is to isolate memory into a few fixed partitions. Each partition contains precisely one process. The level of multi-programming relies upon the number of partitions. In the different partition technique, when a par
7 min read
Memory Management in Operating System
The term memory can be defined as a collection of data in a specific format. It is used to store instructions and process data. The memory comprises a large array or group of words or bytes, each with its own location. The primary purpose of a computer system is to execute programs. These programs, along with the information they access, should be
14 min read
Levels of Memory in Operating System
Memory hierarchy of a computer system it handles differences in speed. "Hierarchy" is a great way to say "order of thinks" like top to bottom, fast to slow, most important to least important. If you look at the memory hierarchy inside the computer, according to the fastest to the slowest: 1. CPU Registers 2. Caches memory 3. Main or Primary Memory
3 min read
Memory Allocation Techniques | Mapping Virtual Addresses to Physical Addresses
Prerequisite : Requirements of Memory Management System, Logical and Physical Address Memory Allocation Techniques:To store the data and to manage the processes, we need a large-sized memory and, at the same time, we need to access the data as fast as possible. But if we increase the size of memory, the access time will also increase and, as we kno
5 min read
Difference between Virtual Memory and Job Pool
Virtual Memory :Virtual memory is a memory management technique in the operating system that gives users the illusion that they are working with memory that is equal to the memory of secondary storage medium ( that is very large memory). Thus, this allows a programmer to write a program that requires more memory than the actual memory.Job Pool :A j
3 min read
Virtual Memory | Questions
Advantages Large virtual memory. More efficient use of memory. Unconstrained multiprogramming. There is no limit on degree of multiprogramming. Disadvantages Number of tables and amount of processor overhead for handling page interrupts are greater than in the case of the simple paged management techniques. Due to lack of an explicit constraint on
2 min read
Allocating kernel memory (buddy system and slab system)
Prerequisite - Buddy System Introduction: Allocating kernel memory is a critical task in operating system design, as the kernel needs to manage memory efficiently and effectively to ensure optimal system performance. Two common methods for allocating kernel memory are the buddy system and the slab system. The buddy system is a memory allocation alg
9 min read
Why Linked List is implemented on Heap memory rather than Stack memory?
Pre-requisite: Linked List Data StructureStack vsHeap Memory Allocation The Linked List is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers. It is implemented on the heap memory rather than the stack memory. This article discusses the reason behind
14 min read
Random Access Memory (RAM) and Read Only Memory (ROM)
Memory is a fundamental component of computing systems, essential for performing various tasks efficiently. It plays a crucial role in how computers operate, influencing speed, performance, and data management. In the realm of computer memory, two primary types stand out: Random Access Memory (RAM) and Read-Only Memory (ROM). Understanding the diff
8 min read
Difference between Volatile Memory and Non-Volatile Memory
Memory is one of the most fundamental components in computing systems. Broadly, computer memory can be divided into two types namely volatile memory and non volatile memory. Even though both are crucial in the total functioning of the electronics, they are not interchangeable, each playing specific roles. Volatile memory deploys power in order to s
6 min read
System Protection in Operating System
Introduction: System protection in an operating system refers to the mechanisms implemented by the operating system to ensure the security and integrity of the system. System protection involves various techniques to prevent unauthorized access, misuse, or modification of the operating system and its resources. There are several ways in which an op
3 min read
User View Vs Hardware View Vs System View of Operating System
User View of Operating System: The Operating System is an interface, hides the details which must be performed and present a virtual machine to the user that makes it easier to use. Operating System provides the following services to the user. Execution of a programAccess to I/O devicesControlled access to filesError detection (Hardware failures, a
1 min read
Xv6 Operating System -adding a new system call
Prerequisite - Xv6 Operating System -add a user program In last post we got to know how to add user program in Xv6 Operating System. Now here you will see how to add new system call in Xv6 Operating System. A dding new system call to xv6: A system call is way for programs to interact with operating system. A computer program makes system call when
6 min read
Traps and System Calls in Operating System (OS)
Traps and system calls are two mechanisms used by an operating system (OS) to perform privileged operations and interact with user-level programs. Here is an overview of each mechanism: Traps: A trap is an interrupt generated by the CPU when a user-level program attempts to execute a privileged instruction or encounters an error. When a trap occurs
3 min read
Fork System Call in Operating System
In many operating systems, the fork system call is an essential operation. The fork system call allows the creation of a new process. When a process calls the fork(), it duplicates itself, resulting in two processes running at the same time. The new process that is created is called a child process. It is a copy of the parent process. The fork syst
5 min read
System Programs in Operating System
System Programming can be defined as the act of building Systems Software using System Programming Languages. According to Computer Hierarchy, Hardware comes first then is Operating System, System Programs, and finally Application Programs. Program Development and Execution can be done conveniently in System Programs. Some of the System Programs ar
3 min read
File System Implementation in Operating System
A file is a collection of related information. The file system resides on secondary storage and provides efficient and convenient access to the disk by allowing data to be stored, located, and retrieved. File system implementation in an operating system refers to how the file system manages the storage and retrieval of data on a physical storage de
11 min read
Difference between System Software and Operating System
Software is like a set of instructions that tell a computer what to do. There are two main types application software and system software. Application software is extra programs you can add to your computer to do specific things, like write documents or play games. You don't need these to use your computer, but they help you do particular tasks. Sy
5 min read
Operating Systems | Memory Management | Question 1
Which of the following page replacement algorithms suffers from Belady’s anomaly? (A) FIFO (B) LRU (C) Optimal Page Replacement (D) Both LRU and FIFO Answer: (A) Explanation: Belady’s anomaly proves that it is possible to have more page faults when increasing the number of page frames while using the First in First Out (FIFO) page replacement algor
1 min read
Operating Systems | Memory Management | Question 2
What is the swap space in the disk used for? (A) Saving temporary html pages (B) Saving process data (C) Storing the super-block (D) Storing device drivers Answer: (B) Explanation: Swap space is typically used to store process data. See this for more details.
1 min read
Operating Systems | Memory Management | Question 10
Increasing the RAM of a computer typically improves performance because: (A) Virtual memory increases (B) Larger RAMs are faster (C) Fewer page faults occur (D) Fewer segmentation faults occur Answer: (C) Explanation: When there is more RAM, there would be more mapped virtual pages in physical memory, hence fewer page faults. A page fault causes pe
1 min read
Operating Systems | Memory Management | Question 4
A computer system supports 32-bit virtual addresses as well as 32-bit physical addresses. Since the virtual address space is of the same size as the physical address space, the operating system designers decide to get rid of the virtual memory entirely. Which one of the following is true? (A) Efficient implementation of multi-user support is no lon
1 min read
Operating Systems | Memory Management | Question 5
A CPU generates 32-bit virtual addresses. The page size is 4 KB. The processor has a translation look-aside buffer (TLB) which can hold a total of 128 page table entries and is 4-way set associative. The minimum size of the TLB tag is: (A) 11 bits (B) 13 bits (C) 15 bits (D) 20 bits Answer: (C) Explanation: Size of a page = 4KB = 2^12 Total number
1 min read
Operating Systems | Memory Management | Question 6
Virtual memory is (A) Large secondary memory (B) Large main memory (C) Illusion of large main memory (D) None of the above Answer: (C) Explanation: Virtual memory is illusion of large main memory.
1 min read
Operating Systems | Memory Management | Question 10
Page fault occurs when (A) When a requested page is in memory (B) When a requested page is not in memory (C) When a page is corrupted (D) When an exception is thrown Answer: (B)Explanation: Page fault occurs when a requested page is mapped in virtual address space but not present in memory. Quiz of this QuestionPlease comment below if you find anyt
1 min read
Operating Systems | Memory Management | Question 8
Thrashing occurs when (A) When a page fault occurs (B) Processes on system frequently access pages not memory (C) Processes on system are in running state (D) Processes on system are in waiting state Answer: (B) Explanation: Thrashing occurs processes on system require more memory than it has. If processes do not have “enough” pages, the pagefault
1 min read
Operating Systems | Memory Management | Question 9
A computer uses 46–bit virtual address, 32–bit physical address, and a three–level paged page table organization. The page table base register stores the base address of the first–level table (T1), which occupies exactly one page. Each entry of T1 stores the base address of a page of the second–level table (T2). Each entry of T2 stores the base add
2 min read