Memory related interfaces

Next let’s talk about interfaces. Interfaces are like an interaction point for communication. The role that interfaces play in the kernel layer/driver layer and application layer is similar to the role that registers play in hardware and software . Broadly speaking, it is like protocol specifications in communication. At work, when kernel/driver engineers connect with application development engineers, they also communicate through interfaces.

The memory interface is still very important in the development process; just like the application layer development, the related function interfaces for string family processing are important and commonly used.

Here is a brief summary of the following interfaces and application scenarios:

Kernel layer : kmalloc and kfree, vmalloc and vfree, kzalloc, kcalloc, alloc_pages, devm_kzalloc

kmalloc is a common solution for memory allocation in the kernel. Applicable scenario: continuous physical pages

Commonly used parameters: GFP_KERNEL and GFP_ATOMIC.

GFP_ATOMIC: performs high-priority allocation without sleep, suitable for interrupt handlers and other code segments that cannot sleep;

GFP_KERNEL: For sleepable code segments, such as process context code without spin locks.

vmalloc: The memory virtual address is continuous but the physical address is not guaranteed to be continuous. Map physical memory into contiguous logical address space (there is a performance loss).

alloc_page: Allocate high-end memory and allocate page size. Note that the function return value is a pointer to the execution struct page structure.

kzalloc: Compared with kmalloc, a flag is added to clear the applied content. __GFP_ZERO

kcalloc: Allocate memory for the array.

Application layer : mallloc, calloc, realloc and mmap (function library)

Difference: Differences in applicable scenarios, performance and functions

Scenario: malloc+memset = calloc

Performance: calloc has only half the assembly instructions of malloc

Functionally: realloc can adjust the size of memory allocated by malloc and increase the memory to size .

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
 
int main()
{
   char *str;
 
   /* 最初的内存分配 */
   str = (char *) malloc(5*sizeof(int));
   strcpy(str, "aaaaaaaaaaaaaaaaaaaabbbb");
   printf("String = %s,  Address = %u\n", str, str);
 
   /* 重新分配内存 */
   str = (char *) realloc(str,7*sizeof(int));
   strcat(str, ".com");
   printf("String = %s,  Address = %u\n", str, str);
 
   free(str);
 
   return(0);
}

Part of the underlying implementation of malloc is mmap. That is to say, the implementation of malloc calls sys_mmap to allocate memory when it is greater than 128k; when it is less than 128k, it calls sys_brk.

The implementation principle and usage of the mmap interface will be discussed separately later.

Guess you like

Origin blog.csdn.net/tanxiezang5399/article/details/122513658