Memory Management in Operating Systems
Memory Management in Operating Systems
of ISE,
Operating Systems Memory Management DBIT
(BCS303)
Module IV
Memory Management
4.1 Background:
4.1.1 Basic Hardware:
Main memory and the registers built into the processor itself are the only storage that
the CPUcan access directly.
There are machine instructions that take memory addresses as arguments, but none
that takedisk addresses.
Therefore, any instructions in execution, and any data being used by the instructions,
must bein one of these direct-access storage devices.
Registers that are built into the CPU are generally accessible within one cycle of
the CPUclock.
Most CPUs can decode instructions and perform simple operations on register contents
at therate of one or more operations per clock tick.
Fig. 4.1 A base and limit register define a logical address space
We can provide the protection by using two registers, usually a base and a limit, as
illustratedin Figure 4.1.
The base register holds the smallest legal physical memory address; the limit register
specifiesthe size of the range.
For example, if the base register holds 300040 and limit register is 120900, then the
program can legally access all addresses from 300040 through 420940 (inclusive).
Protection of memory space is accomplished by having the CPU hardware compare
every address generated in user mode with the registers.
Any attempt by a program executing in user mode to access operating-system memory
or other users' memory results in a trap to the operating system, which treats the attempt
as a fatal error (Figure 4.2). This scheme prevents a user program from (accidentally or
deliberately) modifying the code or data structures of either the operating system or
other users.
Subject Module 4 Prepared by: Dept. of ISE,
Operating Systems Memory Management DBIT
(BCS303)
Fig. 4.2 Hardware address protection with base and limit registers
Figure 4.4 shows that dynamic re-location which implies mapping from virtual
(logical)addresses space to physical address space and is performed by the hardware at
run time.
The value in the relocation register is added to every address generated by a user
process at thetime the address is sent to memory
Re-location is performed by the hardware and is invisible to the user.
Dynamic relocation makes it possible to move a partially executed process from one
area ofmemory to another without affecting.
Static linking – system libraries and program code combined by the loader into
the binaryprogram image.
Dynamic linking –linking postponed until execution time
Small piece of code, stub, used to locate the appropriate memory-resident library routine.
Stub replaces itself with the address of the routine, and executes the routine
Operating system checks if routine is in processes’ memory address
If not in address space, add to address space
Dynamic linking is particularly useful for libraries
System also known as shared libraries
Consider applicability to patching system libraries
Versioning may be needed
Subject Module 4 Prepared by: Dept. of ISE,
Operating Systems Memory Management DBIT
(BCS303)
4.2 Swapping
First-fit:
212K is put in 500K partition
417K is put in 600K partition
112K is put in 288K partition (new partition 288K = 500K -
212K)
426K must wait
Best-fit:
212K is put in 300K partition
417K is put in 500K partition
112K is put in 200K partition
426K is put in 600K partition
Worst-fit:
212K is put in 600K partition
417K is put in 500K partition
112K is put in 388K partition
426K must wait
In this example, best-fit turns out to be the best.
Subject Module 4 Prepared by: Dept. of ISE,
Operating Systems Memory Management DBIT
(BCS303)
4.3.3 Fragmentation
As processes are loaded and removed from memory, the free memory space is broken into
littlepieces.
External fragmentation exists when there is enough total memory space to satisfy a
request but the available spaces are not contiguous; storage is fragmented into a large
number of small holes.
This fragmentation problem can be severe.
Depending on the total amount of memory storage and the average process size, external
fragmentation may be a minor or a major problem.
Statistical analysis of first fit, for instance, reveals that, even with some optimization,
given N allocated blocks, another 0.5 N blocks will be lost to fragmentation. That is, one-
third of memory may be unusable! This property is known as the 50-percent rule.
Memory fragmentation can be internal as well as external.
Consider a multiple-partition allocation scheme with a hole of 18,464 bytes. Suppose that
the next process requests 18,462 bytes. If we allocate exactly the requested block, we are
left witha hole of 2 bytes.
The overhead to keep track of this hole will be substantially larger than the hole itself.
The general approach to avoiding this problem is to break the physical memory into
fixed-sized blocks and allocate memory in units based on block size.
With this approach, the memory allocated to a process may be slightly larger than the
requested memory. The difference between these two numbers is internal fragmentation
that is unused memory that is internal to a partition.
One solution to the problem of external fragmentation is compaction. The goal is to
shuffle the memory contents so as to place all free memory together in one large block.
Compaction is not always possible.
Another possible solution to the external-fragmentation problem is to permit the logical
address space of the processes to be noncontiguous, thus allowing a process to be
allocated physical memory wherever such memory is available.
4.4.1 Paging
Basic Method
Paging is a memory-management scheme that permits the physical address space of a
processto be noncontiguous.
Paging avoids external fragmentation and the need for compaction.
It also solves the considerable problem of fitting memory chunks of varying sizes onto the
backing store.
The basic method for implementing paging involves breaking physical memory into
fixed- sized blocks called frames and breaking logical memory into blocks of the same
size called pages.
When a process is to be executed, its pages are loaded into any available memory frames
from their source. The hardware support for paging is illustrated in Figure 4.8
Every address generated by the CPU is divided into two parts: a page number (p) and a
page offset (d). The page number is used as an index into a page table.
The page table contains the base address of each page in physical memory. This base
Subject Module 4 Prepared by: Dept. of ISE,
Operating Systems Memory Management DBIT
(BCS303)
address is combined with the page offset to define the physical memory address that is
sent to thememory unit.
The size of a page is typically a power of 2, varying between 512 bytes and 16 MB per
page, depending on the computer architecture.
The selection of a power of 2 as a page size makes the translation of a logical address into
a page number and page offset particularly easy.
If the size of logical address space is 2m and a page size is 2n addressing units (bytes or
words), then the high-order m – n bits of a logical address designate the page number, and
the n low- order bits designate the page offset.
Thus, the logical address is as follows:
If the page number is found, its frame number is immediately available and is used to
access memory.
The whole task may take less than 10 percent longer than it would if an unmapped
memory reference were used.
If the page number is not in the TLB (known as a TLB miss), a memory reference to the
page table must be made.
The percentage of times that a particular page number is found in the TLB is called the hit
ratio.
An 80-percent hit ratio means that we find the desired page number in the TLB 80 percent
of the time.
If it takes 20 nanoseconds to search the TLB and 100 nanoseconds to access memory,
then a mapped-memory access takes 120 nanoseconds when the page number is in the
TLB.
If we fail to find the page number in the TLB (20 nanoseconds), then we must first access
memory for the page table and frame number (100 nanoseconds) and then access the
desired byte in memory (100 nanoseconds), for a total of 220 nanoseconds.
To find the effective memory-access time, we weight each case by its
probability: Effective access time = 0.80 * 120 + 0.20 * 220 = 140
nanoseconds.
In this example, we suffer a 40-percent slowdown in memory-access time (from 100 to
140 nanoseconds).
For a 98-percent hit ratio,
we have effective access time = 0.98 * 120 + 0.02 * 220 = 122 nanoseconds.
Protection
Memory protection in a paged environment is accomplished by protection bits associated
witheach frame.
Normally, these bits are kept in the page table.
Subject Module 4 Prepared by: Dept. of ISE,
Operating Systems Memory Management DBIT
(BCS303)
Shared Pages
One of the advantages of paging is the possibility of sharing common code.
This consideration is particularly important in a time-sharing environment.
Example: Consider a system that supports 40 users, each of whom executes a text editor.
If the text editor consists of 150 KB of code and 50 KB of data space, we need 8,000 KB
to support the 40 users.
If the code is reentrant code (or pure code), however, it can be shared, as shown in
Figure. 4.12. Here we see a three-page editor—each page 50 KB in size being shared
among three processes. Each process has its own data page.
Reentrant code is non-self-modifying code; it never changes during execution. Thus, two
or more processes can execute the same code at the same time.
Each process has its own copy of registers and data storage to hold the data for the
process's execution. The data for two different processes will, of course, be different.
Only one copy of the editor need be kept in physical memory. Each user's page table maps
onto the same physical copy of the editor, but data pages are mapped onto different
frames. Thus, to support 40 users, we need only one copy of the editor (150 KB), plus 40
copies of the 50 KB of data space per user. The total space required is now 2,150 KB
instead of 8,000 KB - a significant savings.
Subject Module 4 Prepared by: Dept. of ISE,
Operating Systems Memory Management DBIT
(BCS303)
4.4.2 Segmentation
Consider how you think of a program when you are writing it. You think of it as a main
program with a set of methods, procedures, or functions. (Figure 4.13)
It may also include various data structures: objects, arrays, stacks, variables, and so on.
Each of these modules or data elements is referred to by name. You talk about "the stack,"
"the math library," ''the main program," without caring what addresses in memory these
elements occupy.
The user therefore specifies each address by two quantities: a segment name and an offset.
(Contrast this scheme with the paging scheme, in which the user specifies only a single
address, which is partitioned by the hardware into a page number and an offset, all
invisible to the programmer.)
For simplicity of implementation, segments are numbered and are referred to by a
segment number, rather than by a segment name.
Thus, a logical address consists of a two tuple: < segment-number, offset >.
Although the user can now refer to objects in the program by a two-dimensional
address, the actual physical memory is still, of course, a one-dimensional sequence of
bytes.
This is done with the help of segment table. Each entry in the segment table has a
segmentbase and a segment limit.
The segment base contains the starting physical address where the segment resides in
memory,whereas the segment limit specifies the length of the segment.
The use of a segment table is illustrated in Figure 4.14. A logical address consists of two
parts: asegment number, s, and an offset into that segment, d.
The segment number is used as an index to the segment table.
The offset d of the logical address must be between 0 and the segment limit. If it is not,
we trap to the operating system. When an offset is legal, it is added to the segment base to
produce the address in physical memory of the desired byte.
As an example, consider the situation shown in Figure 4.15.
For example, segment 2 is 400 bytes long and begins at location 4300. Thus, a
reference tobyte 53 of segment 2 is mapped onto location 4300 + 53 = 4353.
A reference to segment 3, byte 852, is mapped to 3200 (the base of segment 3) + 852 =
4052.A reference to byte 1222 of segment 0 would result in a trap to the operating system,
as this segment is only 1,000 bytes long.
Memory structures for paging can get huge using straight-forward methods
o Consider a 32-bit logical address space as on modern computers
o Page size of 4 KB (212)
o Page table would have 1 million entries (232 / 212)
o If each entry is 4 bytes -> 4 MB of physical address space / memory for page
tablealone
That amount of memory used to cost a lot
Don’t want to allocate that contiguously in main memory
Three methods of representing Page Table
1. Hierarchical Paging
2. Hashed Page Tables
3. Inverted Page Tables
Subject Module 4 Prepared by: Dept. of ISE,
Operating Systems Memory Management DBIT
(BCS303)
A logical address (on 32-bit machine with 1K page size) is divided into:
o a page number consisting of 22 bits
o a page offset consisting of 10 bits
Since the page table is paged, the page number is further divided into:
o a 12-bit page number
o a 10-bit page offset
Thus, a logical address is as follows:
where p1 is an index into the outer page table, and p2 is the displacement within the page of
theouter page table
Known as forward-mapped page table –Figure 4.17
Subject Module 4 Prepared by: Dept. of ISE,
Operating Systems Memory Management DBIT
(BCS303)
Figure 4.20 Diagram showing virtual memory that is larger than physical memory.
Subject Module 4 Prepared by: Dept. of ISE,
Operating Systems Memory Management DBIT
(BCS303)
The virtual address space of a process refers to the logical (or virtual) view of how a process
is stored in memory. Typically, this view is that a process begins at a certain logical address—
say, addresses 0—and exists in contiguous memory, as shown in Figure 4.21. We allow for the
heap to grow upward hi memory as it is used for dynamic memory allocation. Similarly, we
allow for the stack to grow downward in memory through successive function calls. The large
blank space (or hole) between the heap and the stack is part of the virtual address space.
Virtual memory also allows files and memory to be shared by two or more processes through
page sharing. This leads to the following benefits:
System libraries can be shared by several processes through mapping of the shared
object intoa virtual address space.
Virtual memory enables processes to share memory.
Virtual memory can allow pages to be shared during process creation with the fork( )
system call, thus speeding up process creation.
4,6.1Demand Paging
A demand-paging system is similar to a paging system with swapping where
processes reside in secondary memory.
When we want to execute a process, we swap it into memory.
Rather than swapping the entire process into memory, however, we use a lazy
swapper. A lazy swapper never swaps a page into memory unless that page will
be needed.
When a process is to be swapped in, the pager guesses which pages will be used
beforethe process is swapped out again.
Instead of swapping in a whole process, the pager brings only those
necessary pagesinto memory.
In page table we maintain a extra bit called valid-invalid bit to know the
status ofpage.
If it is set to 1 then page is valid and present in primary memory, then we
calculate thephysical address and continue execution.
If it is set to 0, then page is not present in primary memory, such a state is
called pagefault. Following procedure is used to handle Page faults. (Fig. 4.24)
1. We check an page table for this process to determine whether the
reference was avalid or an invalid memory access.
2. If the reference was invalid, we terminate the process. Generate trap to
operatingsystems.
3. OS brings page from secondary storage.
4. Find a free frame if available, else use page replacement algorithm to
remove onepage from primary memory to make fare free.
5. We modify the page table to indicate that the page is now in memory.
Subject Module 4 Prepared by: Dept. of ISE,
Operating Systems Memory Management DBIT
(BCS303)
6. We restart the instruction that was interrupted by the trap. The process
can nowaccess the page as though it had always been in memory.
If one access out of 1,000 causes a page fault, the effective access time is 8.2
microseconds. That is page fault is 1/10 or 0.1%.
Subject Module 4 Prepared by: Dept. of ISE,
Operating Systems Memory Management DBIT
(BCS303)
4.6.2 Copy-on-Write
We know that the fork() system call creates a child process as a duplicate of its
parent.
Traditionally, fork() worked by creating a copy of the parent's address space
for the child, duplicating the pages belonging to the parent. However,
considering that manychild processes invoke the exec() system call
immediately after creation, the copying of the parent's address space may be
unnecessary.
Alternatively, we can use a technique known as copy-on-write, which works by
allowing the parent and child processes initially to share the same pages. These
shared pages are marked as copy-on-write pages, meaning that if either process
writes to a shared page, a copy of the shared page is created.
Copy-on-write is illustrated in Figures 4.25 and Figure 4.26, which show the
contents of the physical memory before and after process 1 modifies page C.
For example, assume that the child process attempts to modify a page
containing portions of the stack, with the pages set to be copy-on-write.
The operating system will then create a copy of this page, mapping it to the
address space of the child process.
The child process will then modify its copied page and not the page belonging
to the parent process.
Obviously, when the copy-on-write technique is used, only the pages that are
modified by either process are copied; all unmodified pages can be shared by
the parent and child processes.
If there is no free frame in primary memory and CPU wants to execute a page
which is not present in primary memory this is called page fault. Then we need
to remove one page from primary memory and bring new page from secondary
storage.
Page replacement is process of selecting a page in primary memory to make a
way for new page.
If no frames are free, two page transfers (one out and one in) are required. This
situation effectively doubles the page-fault service time and increases the
effective access time accordingly.
We can reduce this overhead by using a modify bit (or dirty bit). When this
scheme is used, each page or frame has a modify bit associated with it in the
hardware.
The modify bit for a page is set by the hardware whenever any word or byte in
the page is written into, indicating that the page has been modified.
When we select a page for replacement, we examine its modify bit. If the bit is
set, we know that the page has been modified since it was read in from the disk.
In this case, we must write that page to the disk.
If the modify bit is not set, however, the page has not been modified since it was
read into memory. Therefore, if the copy of the page on the disk has not been
overwritten (by some other page, for example), then we need not write the
Subject Module 4 Prepared by: Dept. of ISE,
Operating Systems Memory Management DBIT
(BCS303)
To illustrate the problems that are possible with a FIFO page-replacement algorithm.,
we consider the following reference string: 1,2,3,4,1,2,5,1,2,3,4,5
Figure 4.28 shows the curve of page faults for this reference string versus the number
of available frames. Notice that the number of faults for four frames (ten) is greater
than the number of faults for three frames (nine)! This most unexpected result is known
as Belady's anomaly: For some page-replacement algorithms, the page-fault rate may
increase as the number of allocated frames increases.
If we use the recent past as an approximation of the near future, then we can
replace the page that has not been used for the longest period of time (Figure
4.30). This approach is the least-recently-used (LRU) algorithm.
Replace the page that has not been used for the longest period of time
Counters: In the simplest case, we associate with each page-table entry a time-of-use field and
add to the CPU a logical clock or counter. The clock is incremented for every memory
reference. Whenever a reference to a page is made, the contents of the clock register are copied
to the time-of-use field in the page-table entry for that page. In this way, we always have the
"time" of the last reference to eachpage. We replace the page with the smallest time value.
Stack: Another approach to implementing LRU replacement is to keep a stack of page
numbers. Whenever a page is referenced, it is removed from the stack and put on the top. In this
way, the most recently used page is always at the top of the stack and the least recently used
page is always at the bottom (Figure 4.31).
Additional-Reference-Bits Algorithm
• We can gain additional ordering information by recording the reference bits at regular
intervals.
• We can keep an 8-bit byte for each page in a table in memory.
• At regular intervals (say, every 100 milliseconds), a timer interrupt transfers
control to theoperating system.
• The operating system shifts the reference bit for each page into the high-order bit of
its 8-bitbyte, shifting the other bits right by 1 bit and discarding the low-order bit.
• These 8-bit shift registers contain the history of page use for the last eight time periods.
Second-Chance Algorithm
• The basic algorithm of second-chance replacement is a FIFO replacement algorithm.
• When a page has been selected, however, we inspect its reference bit.
• If the value is 0, we proceed to replace this page; but if the reference bit is set to 1, we
give thepage a second chance and move on to select the next FIFO page.
• When a page gets a second chance, its reference bit is cleared, and its arrival time is
reset to thecurrent time.
• Thus, a page that is given a second chance will not be replaced until all other pages
have beenreplaced.
• The most frequently used (MFU) page-replacement algorithm is based on the argument that
the pagewith the smallest count was probably just brought in and has yet to be used.
Subject Module 4 Prepared by: Dept. of ISE,
Operating Systems Memory Management DBIT
(BCS303)
4.6.5Allocation of Frames
How do we allocate the fixed amount of free memory among the various processes? If
we have93 free frames and two processes, how many frames does each process get?
The simplest case is the single-user system. Consider a single-user system with 128 KB
of memory composed of pages 1 KB in size. This system has 128 frames.
The operating system may take 35 KB, leaving 93 frames for the user process. Under
pure demand paging, all 93 frames would initially be put on the free-frame list. When a
user processstarted execution, it would generate a sequence of page faults.
The first 93 page faults would all get free frames from the free-frame list. When the
free-framelist was exhausted, a page-replacement algorithm would he used to select one
of the 93 in- memory pages to be replaced with the 94th, and so on.
When the process terminated, the 93 frames would once again be placed on the free-frame
list.
Allocation Algorithms
The easiest way to split m frames among n processes is to give everyone an equal share,
m/n
frames.
For instance, if there are 93 frames and five processes, each process will get 18
frames. Theleftover three frames can be used as a free-frame buffer pool.
This scheme is called equal allocation.
An alternative is to recognize that various processes will need differing
amounts of [Link] a system with a 1-KB frame size. If a small student
Subject Module 4 Prepared by: Dept. of ISE,
Operating Systems Memory Management DBIT
(BCS303)
process of 10 KB and an interactive database of 127 KB are the only two processes
running in a system with 62 free frames, it does not make much sense to give each
process 31 frames. The student process does not need more than 10 frames, so the other
21 are, strictly speaking, wasted. To solve this problem, we can use proportional
allocation, in which we allocate available memory to each process according to its size.
4.7 Thrashing
If the process does not have the number of frames it needs to support pages in active
use, it willquickly page-fault. At this point, it must replace some page.
However, since all its pages are in active use, it must replace a page that will be
needed again right away. Consequently, it quickly faults again, and again, and again,
replacing pages that it must bring back in immediately.
This high paging activity is called thrashing. A process is thrashing if it is spending
more timepaging than executing.
Cause of Thrashing
Thrashing results in severe performance problems.
The operating system monitors CPU utilization. If CPU utilization is too low, we
increase the degree of multiprogramming by introducing a new process to the system.
A global page-replacement algorithm is used; it replaces pages without regard to the
process towhich they belong.
Now suppose that a process enters a new phase in its execution and needs more frames.
It startsfaulting and taking frames away from other processes.
These processes need those pages, however, and so they also fault, taking frames from
other processes. These faulting processes must use the paging device to swap pages in
and out. As they queue up for the paging device, the ready queue empties. As processes
wait for the pagingdevice, CPU utilization decreases.
Subject Module 4 Prepared by: Dept. of ISE,
Operating Systems Memory Management DBIT
(BCS303)
We can limit the effects of thrashing by using a local replacement algorithm (or
priority replacement algorithm). With local replacement, if one process starts
thrashing, it cannot steal frames from another process and cause the latter to thrash as
well.
Working-Set Model
The working-set model is based on the assumption of locality.
This model uses a parameter, A, to define the working-set window.
The idea is to examine the most recent A page references.
The set of pages in the most recent A page references is the working set (Figure 9.20).
where D is the total demand for frames. Each process is actively using the pages in its working set.
Page-Fault Frequency :
The working-set model is successful, and knowledge of the working set can be
useful forprepaging but it seems a clumsy way to control thrashing.
A strategy that uses the page-fault frequency (PFF) takes a more direct approach.
Thrashing has a high page-fault rate.
Thus, we want to control the page-fault rate.
When it is too high, we know that the process needs more frames.
Conversely, if the page-fault rate is too low, then the process may have too many frames.
We can establish upper and lower bounds on the desired page-fault rate (Figure 9.21).
If the actual page-fault rate exceeds the upper limit, we allocate the process another frame;
If the page-fault rate falls below the lower limit, we remove a frame from the process.
Thus, we can directly measure and control the page-fault rate to prevent thrashing.
Subject Module 4 Prepared by: Dept. of ISE,
Operating Systems Memory Management DBIT
(BCS303)
Problems:
1. Consider the following page reference string
8,1,2,3,1,4,1,5,3,4,1,4,3,2,3,1,2,8,1,2
Assuming there are 4 memory frames, how many page faults would occur in case of
i. FIFO
ii. Optimal algorithm,
Note that initially all frames are empty.
Sol:
i. FIFO Replacement
8 1 2 3 1 4 1 5 3 4 1 4 3 2 3 1 2 8 1 2
8 8 8 8 4 4 4 4 3 3
1 1 1 1 5 5 5 5 8
2 2 2 2 1 1 1 1
3 3 3 3 2 2 2
8 1 2 3 1 4 1 5 3 4 1 4 3 2 3 1 2 8 1 2
8 8 8 8 4 4 2 2
1 1 1 1 1 1 1
2 2 2 5 5 8
3 3 3 3 3
Question Bank
1. Describe the Segmentation technique.
2. What is Paging? Explain the Structure of Page Table.
3. What is Swapping? Does this increase OS overhead? Justify your answer.
4. What are Translation Load side Buffer(TLB)?Explain TLB in detail with a
simple paging system with a neat diagram.
5. Write a note on Contiguous memory allocation.
6. Module-4
7. Describe briefly about demand paging in memory management scheme.
8. Illustrate how demand paging affects system performance.
9. Describe the steps involved handling a page fault.
10. What is Thrashing? How it can be controlled?
11. 1. Consider the following page reference string
7,0,1,2,0,3,0,4,2,3,0,3,2,1,2,0,1,7,0,1
Assuming there are 2 memory frames, how many page faults would occur in case of
i) LRU
ii) ii) Optimal algorithm,
Note that initially all frames are empty.
Subject Module 4 Prepared by: Dept. of ISE,
Operating Systems Memory Management DBIT
(BCS303)
1. Discuss the issues that are pertinent to the various techniques for managing memory.
2. Write a note on dynamic Loading and Linking.
3. What is swapping? Does this increase OS overhead? Justify your answer.
4. Write a note on Contiguous memory allocation.
5. What is internal & external fragmentation?
6. Bring out differences between internal & external fragmentation? How are they overcome?
7. Explain the buddy-system, used for managing free memory assigned to kernel process.
8. What is paging? Explain basic hardware of paging.
9. Why TLB is important. In simple paging what information is stored in TLB.
10. Write a note on shared pages.
11. Describe the Segmentation technique.