The Wayback Machine - https://web.archive.org/web/20240926192753/https://www.geeksforgeeks.org/operating-system-allocating-kernel-memory-buddy-system-slab-system/
Open In App

Allocating kernel memory (buddy system and slab system)

Last Updated : 14 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 algorithm that works by dividing memory into blocks of a fixed size, with each block being a power of two in size. When a request for memory is made, the algorithm finds the smallest available block of memory that is large enough to satisfy the request. If the block is larger than the requested size, it is split into two smaller blocks of equal size (the “buddies”), with each buddy being marked as either allocated or free. The algorithm then continues recursively until it finds the exact size of the requested memory or a block that is the smallest possible size.

The slab system is a memory allocation algorithm that is designed specifically for kernel memory. It works by dividing memory into fixed-size caches or slabs, each of which contains a set of objects of the same type. When a request for memory is made, the algorithm first checks if there is an available object in the appropriate slab cache. If there is, the object is returned. If not, the algorithm allocates a new slab and adds it to the appropriate cache.

The advantages of the buddy system are that it is easy to implement and can handle a wide range of memory sizes. The disadvantages are that it can lead to memory fragmentation and that it can be inefficient for allocating small amounts of memory.

The advantages of the slab system are that it is efficient for allocating small amounts of memory and that it can prevent memory fragmentation. The disadvantages are that it can be more complex to implement than the buddy system and that it may require more memory overhead.

Overall, both the buddy system and the slab system are effective methods for allocating kernel memory, and the choice between the two depends on the specific needs and requirements of the operating system being developed.
Two strategies for managing free memory that is assigned to kernel processes:

1. Buddy system –

Buddy allocation system is an algorithm in which a larger memory block is divided into small parts to satisfy the request. This algorithm is used to give best fit. The two smaller parts of block are of equal size and called as buddies. In the same manner one of the two buddies will further divide into smaller parts until the request is fulfilled. Benefit of this technique is that the two buddies can combine to form the block of larger size according to the memory request. 

Example – If the request of 25Kb is made then block of size 32Kb is allocated. 

Four Types of Buddy System – 

  1. Binary buddy system
  2. Fibonacci buddy system
  3. Weighted buddy system
  4. Tertiary buddy system

Why buddy system? 
If the partition size and process size are different then poor match occurs and may use space inefficiently. 
It is easy to implement and efficient then dynamic allocation. 

Binary buddy system – 
The buddy system maintains a list of the free blocks of each size (called a free list), so that it is easy to find a block of the desired size, if one is available. If no block of the requested size is available, Allocate searches for the first non-empty list for blocks of atleast the size requested. In either case, a block is removed from the free list. 

Example – Assume the size of memory segment is initially 256kb and the kernel requests 25kb of memory. The segment is initially divided into two buddies. Let we call A1 and A2 each 128kb in size. One of these buddies is further divided into two 64kb buddies let say B1 and B2. But the next highest power of 25kb is 32kb so, either B1 or B2 is further divided into two 32kb buddies(C1 and C2) and finally one of these buddies is used to satisfy the 25kb request. A split block can only be merged with its unique buddy block, which then reforms the larger block they were split from. 

Fibonacci buddy system – 
This is the system in which blocks are divided into sizes which are Fibonacci numbers. It satisfies the following relation: 

  Zi = Z(i-1)+Z(i-2)

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 144, 233, 377, 610. The address calculation for the binary and weighted buddy systems is straight forward, but the original procedure for the Fibonacci buddy system was either limited to a small, fixed number of block sizes or a time consuming computation. 

Advantages – 

  • In comparison to other simpler techniques such as dynamic allocation, the buddy memory system has little external fragmentation.
  • The buddy memory allocation system is implemented with the use of a binary tree to represent used or unused split memory blocks.
  • The buddy system is very fast to allocate or deallocate memory.
  • In buddy systems, the cost to allocate and free a block of memory is low compared to that of best-fit or first-fit algorithms.
  • Other advantage is coalescing.
  • Address calculation is easy.
  • Efficient memory management: Kernel memory allocators are designed to efficiently manage memory resources, ensuring that memory is allocated and deallocated in a way that minimizes fragmentation and maximizes available space.
  • Customizable allocation policies: Kernel memory allocators can be customized to implement specific allocation policies, such as best fit, worst fit, or first fit. This allows for more precise control over memory usage and allocation.
  • High performance: Kernel memory allocators are typically designed for high-performance systems, allowing for fast and efficient allocation and deallocation of memory.
  • Reduced memory overhead: Memory allocators can reduce memory overhead by allowing for more efficient use of memory resources, reducing the overall memory footprint of the system.
  • Improved system stability: Efficient memory management can help improve system stability by reducing the likelihood of memory leaks, crashes, and other issues related to memory allocation.

Overall, using a kernel memory allocator can help improve system performance, stability, and memory management, making it an essential component of any operating system.

What is coalescing? 
It is defined as how quickly adjacent buddies can be combined to form larger segments this is known as coalescing. 
For example, when the kernel releases the C1 unit it was allocated, the system can coalesce C1 and C2 into a 64kb segment. This segment B1 can in turn be coalesced with its buddy B2 to form a 128kb segment. Ultimately we can end up with the original 256kb segment. 

Drawback – 
The main drawback in buddy system is internal fragmentation as larger block of memory is acquired then required. For example if a 36 kb request is made then it can only be satisfied by 64 kb segment and remaining memory is wasted. 

2. Slab Allocation –

A second strategy for allocating kernel memory is known as slab allocation. It eliminates fragmentation caused by allocations and deallocations. This method is used to retain allocated memory that contains a data object of a certain type for reuse upon subsequent allocations of objects of the same type. In slab allocation memory chunks suitable to fit data objects of certain type or size are preallocated. Cache does not free the space immediately after use although it keeps track of data which are required frequently so that whenever request is made the data will reach very fast. Two terms required are:  

  • Slab – A slab is made up of one or more physically contiguous pages. The slab is the actual container of data associated with objects of the specific kind of the containing cache.
  • Cache – Cache represents a small amount of very fast memory. A cache consists of one or more slabs. There is a single cache for each unique kernel data structure.

12

Example –  

  • A separate cache for a data structure representing processes descriptors
  • Separate cache for file objects
  • Separate cache for semaphores etc.

Each cache is populated with objects that are instantiations of the kernel data structure the cache represents. For example the cache representing semaphores stores instances of semaphore objects, the cache representing process descriptors stores instances of process descriptor objects. 

Implementation – 
The slab allocation algorithm uses caches to store kernel objects. When a cache is created a number of objects which are initially marked as free are allocated to the cache. The number of objects in the cache depends on size of the associated slab. 
Example – A 12 kb slab (made up of three contiguous 4 kb pages) could store six 2 kb objects. Initially all objects in the cache are marked as free. When a new object for a kernel data structure is needed, the allocator can assign any free object from the cache to satisfy the request. The object assigned from the cache is marked as used. 

In linux, a slab may in one of three possible states:  

  1. Full – All objects in the slab are marked as used
  2. Empty – All objects in the slab are marked as free
  3. Partial – The slab consists of both

The slab allocator first attempts to satisfy the request with a free object in a partial slab. If none exists, a free object is assigned from an empty slab. If no empty slabs are available, a new slab is allocated from contiguous physical pages and assigned to a cache. 

Benefits of slab allocator – 

  • No memory is wasted due to fragmentation because each unique kernel data structure has an associated cache.
  • Memory request can be satisfied quickly.
  • The slab allocating scheme is particularly effective for managing when objects are frequently allocated or deallocated. The act of allocating and releasing memory can be a time consuming process. However, objects are created in advance and thus can be quickly allocated from the cache. When the kernel has finished with an object and releases it, it is marked as free and return to its cache, thus making it immediately available for subsequent request from the kernel.


Similar Reads

Buddy System - Memory Allocation Technique
Static partition techniques are limited by having a fixed number of active processes, and space use may not be optimal. The buddy system is a memory allocation and management technique that uses power-of-two increments. Assume the memory size is 2U and a size of S is required. In this article, we are going to discuss the Buddy System in detail alon
8 min read
Buddy Memory Allocation Program | Set 1 (Allocation)
Prerequisite - Buddy System Question: Write a program to implement the buddy system of memory allocation in Operating Systems.Explanation - The buddy system is implemented as follows- A list of free nodes, of all the different possible powers of 2, is maintained at all times (So if total memory size is 1 MB, we'd have 20 free lists to track-one for
13 min read
Buddy Memory Allocation Program | Set 2 (Deallocation)
Prerequisite - Buddy Allocation | Set 1 Question: Write a program to implement the buddy system of memory allocation and deallocation in Operating Systems.Explanation - As we already know from Set 1, the allocation is done via the usage of free lists. Now, for deallocation, we will maintain an extra data structure-a Map (unordered_set in C++, HashM
15+ min read
Difference between Micro Kernel and Modular Kernel
Prerequisite - Kernel in Operating System 1. MicroKernel:Micro Kernel, as the name suggests, is basically a software or code that usually contains a minimum number of functions that are required, data, and features simply to implement OS. It is a very small kernel and represents well studied OS structuring idea. In simple words, micro kernels are r
3 min read
Power-of-Two Free Lists Allocators | Kernel Memory Allocators
The Power of Two Free Lists is an algorithm for Kernel Memory Allocation. It is used frequently to implement malloc() and free() in the user-level C library. This approach uses a set of free lists. Each list stores buffers of a particular size and all the sizes are powers of two. For example, consider the figure below there are six free lists, stor
4 min read
Difference between Operating System and Kernel
In the world of computing, two terms that are frequently mentioned are Operating System (OS) and Kernel. While they are closely related, they serve different purposes within a computer system. Understanding the difference between the two can help clarify how computers function and why both are essential for smooth operation. In this article, we wil
4 min read
Kernel Level Threads in Operating System
Pre-requisites: Thread in Operating System An operating system is a program loaded into a system or computer. and manage all the other program which is running on that OS Program, it manages the all other application programs. or in other words, we can say that the OS is an interface between the user and computer hardware. So, in this article, we w
4 min read
Kernel I/O Subsystem in Operating System
The kernel provides many services related to I/O. Several services such as scheduling, caching, spooling, device reservation, and error handling - are provided by the kernel's I/O subsystem built on the hardware and device-driver infrastructure. The I/O subsystem is also responsible for protecting itself from errant processes and malicious users. I
7 min read
Kernel in Operating System
A kernel is a central component of an operating system that manages the operations of computers and hardware. It basically manages operations of memory and CPU time. It is a core component of an operating system. Kernel acts as a bridge between applications and data processing performed at the hardware level using inter-process communication and sy
10 min read
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
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
Relationship between User level thread and Kernel level thread
Introduction: User-level threads and kernel-level threads are two different approaches to implementing thread management in an operating system. User-level threads are managed entirely by the application, without any involvement from the operating system kernel. The application manages the creation, scheduling, and synchronization of threads, using
9 min read
Difference between Process and Kernel Thread
1. Process: Process is an activity of executing a program. Process is of two types - User process and System process. Process control block controls the operation of the process. 2. Kernel Thread: Kernel thread is a type of thread in which threads of a process are managed at kernel level. Kernel threads are scheduled by operating system (kernel mod
1 min read
What is Terminal, Console, Shell and Kernel?
As a fresher, while learning Linux we get confused with the actual meaning of the terms like-Terminal, Console, Shell, and Kernel. Sometimes we mix up their usage which is technically incorrect so having a clear grasp of what every word actually means and how and where they should be used is very important. 1. Terminal:For those having Linux OS, wh
4 min read
User mode and Kernel mode Switching
In it's life span a process executes in user mode and kernel mode. The User mode is normal mode where the process has limited access. While the Kernel mode is the privileged mode where the process has unrestricted access to system resources like hardware, memory, etc. A process can access I/O Hardware registers to program it, can execute OS kernel
4 min read
Difference between Preemptive and Non-Preemptive Kernel in OS
Introduction : A kernel is the central component of an operating system that manages system resources and provides a layer of abstraction between the hardware and software. One of the key design decisions for a kernel is whether it is preemptive or non-preemptive. A non-preemptive kernel, also known as a cooperative kernel, relies on processes yiel
4 min read
How to extract and disassemble a Linux kernel
Extracting and examining the disassembled assembly code for your Linux kernel can be really helpful if you want to look for some malfunctioning piece of code or want to examine entry points for various functions. The process is fairly intuitive once you know the necessary tools that are required. The process below is described for Ubuntu 20.04 but
3 min read
Monolithic Kernel and Key Differences From Microkernel
Apart from microkernel, Monolithic Kernel is another classification of Kernel. Like microkernel, this one also manages system resources between application and hardware, but user and kernel services are implemented under the same address space. It increases the size of the kernel, thus increasing the size of the operating system as well.  This kern
6 min read
Difference Between Hypervisor and Exo-Kernel
In the context of virtualization and operating system design, it is important to recognize significant dissimilarities between hypervisors and exo-kernels. Both are vital in the administration of hardware resources as well as virtual environments, although they work at different layers and have unique styles of handling resources. Hypervisors are t
4 min read
Difference between User Level thread and Kernel Level thread
User-level threads are threads that are managed entirely by the user-level thread library, without any direct intervention from the operating system's kernel, whereas, Kernel-level threads are threads that are managed directly by the operating system's kernel. In this article, we will see the overview of the User Level thread and Kernel Level threa
5 min read
Difference between Shell and Kernel
In computing, the operating system (OS) serves as the fundamental layer that bridges the gap between computer hardware and the user. Two critical components of an operating system are the kernel and the shell. Understanding the relationship between these two components is fundamental to grasping how operating systems function and how users interact
4 min read
Difference Between User Mode and Kernel Mode
User mode and kernel mode are two working states inside a laptop's working system that determine the level of access and control, a technique can have over machine resources. Understanding the differences among these modes is critical to knowing how modern working systems manage safety and resource allocation. What is User Mode?When a Program is bo
4 min read
Difference Between Microkernel and Monolithic Kernel
In the world of operating systems, the terms "microkernel" and "monolithic kernel" describe two different ways of organizing and managing the core functions of a computer's operating system. The kernel is a computer program at the core of a computer's operating system and has complete control over everything in the system. It manages the operations
5 min read
Why must user threads be mapped to a kernel thread
Prerequisite : Thread in Operating System, Relationship between User level thread and Kernel level thread Introduction : A thread is the basic, atomic unit of CPU utilization in computer systems.Mostly we consider a process to be the basic unit for CPU utilization but a process maybe further divided into multiple threads of execution. A process can
7 min read
What is Reentrant Kernel?
Reentrant Kernel: In kernel mode, a reentrant kernel allows processes (or, more precisely, their corresponding kernel threads) to give up the CPU. They have no effect on other processes entering kernel mode. Multiple processor systems may be scheduled together in the case of single-processor systems. Example: A disc read is an example of this. When
2 min read
Requirements of Memory Management System
Memory management keeps track of the status of each memory location, whether it is allocated or free. It allocates the memory dynamically to the programs at their request and frees it for reuse when it is no longer needed. Memory management meant to satisfy some requirements that we should keep in mind. These Requirements of memory management are:
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