![]() | This article includes a list ofgeneral references, butit lacks sufficient correspondinginline citations. Please help toimprove this article byintroducing more precise citations.(April 2014) (Learn how and when to remove this message) |
Operating systems |
---|
![]() |
Common features |
Memory management (alsodynamic memory management,dynamic storage allocation, ordynamic memory allocation) is a form ofresource management applied tocomputer memory. The essential requirement of memory management is to provide ways to dynamically allocate portions of memory to programs at their request, and free it for reuse when no longer needed. This is critical to any advanced computer system where more than a singleprocess might be underway at any time.[1]
Several methods have been devised that increase the effectiveness of memory management.Virtual memory systems separate thememory addresses used by a process from actual physical addresses, allowing separation of processes and increasing the size of thevirtual address space beyond the available amount ofRAM usingpaging or swapping tosecondary storage. The quality of the virtual memory manager can have an extensive effect on overall systemperformance. The system allows a computer to appear as if it may have more memory available than physically present, thereby allowing multiple processes to share it.
In someoperating systems, e.g.Burroughs/Unisys MCP,[2] andOS/360 and successors,[3] memory is managed by the operating system.[note 1] In other operating systems, e.g.Unix-like operating systems, memory is managed at the application level.
Memory management within an address space is generally categorized as eithermanual memory management or automatic memory management.
The task of fulfilling an allocation request consists of locating a block of unused memory of sufficient size. Memory requests are satisfied by allocating portions from a large pool[note 2] of memory called theheap[note 3] orfree store. At any given time, some parts of the heap are in use, while some are "free" (unused) and thus available for future allocations.In the C language, the function which allocates memory from the heap is calledmalloc
and the function which takes previously allocated memory and marks it as "free" (to be used by future allocations) is calledfree
.[note 4]
Several issues complicate the implementation, such asexternal fragmentation, which arises when there are many small gaps between allocated memory blocks, which invalidates their use for an allocation request. The allocator'smetadata can also inflate the size of (individually) small allocations. This is often managed bychunking. The memory management system must track outstanding allocations to ensure that they do not overlap and that no memory is ever "lost" (i.e. that there are no "memory leaks").
The specific dynamic memory allocation algorithm implemented can impact performance significantly. A study conducted in 1994 byDigital Equipment Corporation illustrates theoverheads involved for a variety of allocators. The lowest averageinstruction path length required to allocate a single memory slot was 52 (as measured with an instruction levelprofiler on a variety of software).[1]
Since the precise location of the allocation is not known in advance, the memory is accessed indirectly, usually through apointerreference. The specific algorithm used to organize the memory area and allocate and deallocate chunks is interlinked with thekernel, and may use any of the following methods:
Fixed-size blocks allocation, also called memory pool allocation, uses afree list of fixed-size blocks of memory (often all of the same size). This works well for simpleembedded systems where no large objects need to be allocated but suffers fromfragmentation especially with long memory addresses. However, due to the significantly reduced overhead, this method can substantially improve performance for objects that need frequent allocation and deallocation, and so it is often used invideo games.
In this system, memory is allocated into several pools of memory instead of just one, where each pool represents blocks of memory of a certainpower of two in size, or blocks of some other convenient size progression. All blocks of a particular size are kept in a sortedlinked list ortree and all new blocks that are formed during allocation are added to their respective memory pools for later use. If a smaller size is requested than is available, the smallest available size is selected and split. One of the resulting parts is selected, and the process repeats until the request is complete. When a block is allocated, the allocator will start with the smallest sufficiently large block to avoid needlessly breaking blocks. When a block is freed, it is compared to its buddy. If they are both free, they are combined and placed in the correspondingly larger-sized buddy-block list.
This memory allocation mechanism preallocates memory chunks suitable to fit objects of a certain type or size.[5] These chunks are called caches and the allocator only has to keep track of a list of free cache slots. Constructing an object will use any one of the free cache slots and destructing an object will add a slot back to the free cache slot list. This technique alleviates memory fragmentation and is efficient as there is no need to search for a suitable portion of memory, as any open slot will suffice.
ManyUnix-like systems as well asMicrosoft Windows implement a function calledalloca
for dynamically allocating stack memory in a way similar to the heap-basedmalloc
. A compiler typically translates it to inlined instructions manipulating the stack pointer.[6] Although there is no need of manually freeing memory allocated this way as it is automatically freed when the function that calledalloca
returns, there exists a risk of overflow. And since alloca is anad hoc expansion seen in many systems but never in POSIX or the C standard, its behavior in case of a stack overflow is undefined.
A safer version of alloca called_malloca
, which reports errors, exists on Microsoft Windows. It requires the use of_freea
.[7]gnulib provides an equivalent interface, albeit instead of throwing an SEH exception on overflow, it delegates to malloc when an overlarge size is detected.[8] A similar feature can be emulated using manual accounting and size-checking, such as in the uses ofalloca_account
in glibc.[9]
The proper management of memory in an application is a difficult problem, and several different strategies for handling memory management have been devised.
In many programming language implementations, the runtime environment for the program automatically allocates memory in thecall stack for non-staticlocal variables of asubroutine, calledautomatic variables, when the subroutine is called, and automatically releases that memory when the subroutine is exited. Special declarations may allow local variables to retain values between invocations of the procedure, or may allow local variables to be accessed by other subroutines. The automatic allocation of local variables makesrecursion possible, to a depth limited by available memory.
Garbage collection is a strategy for automatically detecting memory allocated to objects that are no longer usable in a program, and returning that allocated memory to a pool of free memory locations. This method is in contrast to "manual" memory management where a programmer explicitly codes memory requests and memory releases in the program. While automatic garbage collection has the advantages of reducing programmer workload and preventing certain kinds of memory allocation bugs, garbage collection does require memory resources of its own, and can compete with the application program for processor time.
Reference counting is a strategy for detecting that memory is no longer usable by a program by maintaining a counter for how many independent pointers point to the memory. Whenever a new pointer points to a piece of memory, the programmer is supposed to increase the counter. When the pointer changes where it points, or when the pointer is no longer pointing to any area or has itself been freed, the counter should decrease. When the counter drops to zero, the memory should be considered unused and freed. Some reference counting systems require programmer involvement and some are implemented automatically by the compiler. A disadvantage of reference counting is thatcircular references can develop which cause a memory leak to occur. This can be mitigated by either adding the concept of a "weak reference" (a reference that does not participate in reference counting, but is notified when the area it is pointing to is no longer valid) or by combining reference counting and garbage collection together.
A memory pool is a technique of automatically deallocating memory based on the state of the application, such as the lifecycle of a request or transaction. The idea is that many applications execute large chunks of code which may generate memory allocations, but that there is a point in execution where all of those chunks are known to be no longer valid. For example, in a web service, after each request the web service no longer needs any of the memory allocated during the execution of the request. Therefore, rather than keeping track of whether or not memory is currently being referenced, the memory is allocated according to the request or lifecycle stage with which it is associated. When that request or stage has passed, all associated memory is deallocated simultaneously.
Virtual memory is a method of decoupling the memory organization from the physical hardware. The applications operate on memory viavirtual addresses. Each attempt by the application to access a particular virtual memory address results in the virtual memory address being translated to an actualphysical address.[10] In this way the addition of virtual memory enables granular control over memory systems and methods of access.
In virtual memory systems the operating system limits how aprocess can access the memory. This feature, calledmemory protection, can be used to disallow a process to read or write to memory that is not allocated to it, preventing malicious or malfunctioning code in one program from interfering with the operation of another.
Even though the memory allocated for specific processes is normally isolated, processes sometimes need to be able to share information.Shared memory is one of the fastest techniques forinter-process communication.
Memory is usually classified by access rate intoprimary storage andsecondary storage. Memory management systems, among other operations, also handle the moving of information between these two levels of memory.
An operating system manages various resources in the computing system. The memory subsystem is the system element for managing memory. The memory subsystem combines the hardware memory resource and the MCP OS software that manages the resource.
The memory subsystem manages the physical memory and the virtual memory of the system (both part of the hardware resource). The virtual memory extends physical memory by using extra space on a peripheral device, usually disk. The memory subsystem is responsible for moving code and data between main and virtual memory in a process known as overlaying. Burroughs was the first commercial implementation of virtual memory (although developed at Manchester University for the Ferranti Atlas computer) and integrated virtual memory with the system design of the B5000 from the start (in 1961) needing no external memory management unit (MMU).[11]: 48
The memory subsystem is responsible for mapping logical requests for memory blocks to physical portions of memory (segments) which are found in the list of free segments. Each allocated block is managed by means of a segment descriptor,[12] a special control word containing relevant metadata about the segment including address, length, machine type, and the p-bit or ‘presence’ bit which indicates whether the block is in main memory or needs to be loaded from the address given in the descriptor.
Descriptors are essential in providing memory safety and security so that operations cannot overflow or underflow the referenced block (commonly known as buffer overflow). Descriptors themselves are protected control words that cannot be manipulated except for specific elements of the MCP OS (enabled by the UNSAFE block directive inNEWP).
Donald Knuth describes a similar system in Section 2.5 ‘Dynamic Storage Allocation’ of‘Fundamental Algorithms’.[disputed –discuss]
IBMSystem/360 does not support virtual memory.[note 5] Memory isolation ofjobs is optionally accomplished usingprotection keys, assigning storage for each job a different key, 0 for the supervisor or 1–15. Memory management inOS/360 is asupervisor function. Storage is requested using theGETMAIN
macro and freed using theFREEMAIN
macro, which result in a call to the supervisor (SVC) to perform the operation.
In OS/360 the details vary depending on how the system isgenerated, e.g., forPCP,MFT,MVT.
In OS/360 MVT, suballocation within a job'sregion or the sharedSystem Queue Area (SQA) is based onsubpools, areas a multiple of 2 KB in size—the size of an area protected by a protection key. Subpools are numbered 0–255.[13] Within a region subpools are assigned either the job's storage protection or the supervisor's key, key 0. Subpools 0–127 receive the job's key. Initially only subpool zero is created, and all user storage requests are satisfied from subpool 0, unless another is specified in the memory request. Subpools 250–255 are created by memory requests by the supervisor on behalf of the job. Most of these are assigned key 0, although a few get the key of the job. Subpool numbers are also relevant in MFT, although the details are much simpler.[14] MFT uses fixedpartitions redefinable by the operator instead of dynamic regions and PCP has only a single partition.
Each subpool is mapped by a list of control blocks identifying allocated and free memory blocks within the subpool. Memory is allocated by finding a free area of sufficient size, or by allocating additional blocks in the subpool, up to the region size of the job. It is possible to free all or part of an allocated memory area.[15]
The details forOS/VS1 are similar[16] to those for MFT and for MVT; the details forOS/VS2 are similar to those for MVT, except that the page size is 4 KiB. For both OS/VS1 and OS/VS2 the sharedSystem Queue Area (SQA) is nonpageable.
InMVS the address space[17] includes an additional pageable shared area, theCommon Storage Area (CSA), and two additional private areas, the nonpageablelocal system queue area (LSQA) and the pageableSystem Work area (SWA). Also, the storage keys 0–7 are all reserved for use by privileged code.
alloca(3)
– Linux Programmer'sManual – Library Functions