编程知识 cdmana.com

Linux kernel interview questions (30 questions with answers)

1. Linux What are the main types of kernel locks in ?

Linux The synchronization mechanism of 2.0 To 2.6 Since then, it has been continuously developed and perfected .
From the initial atomic operation , Later The amount of signal , From big kernel locks to today's spinlocks .
The development of these synchronization mechanisms is accompanied by Linux From a single place The transition from processors to symmetric multiprocessors ; With the transition from non preemptive kernel to preemptive kernel .Linux Of Locking mechanisms are becoming more effective , It's getting more and more complicated . Spinlocks can only be held by one executable thread at most , If an executing thread attempts to request a request that has been contested Use has been held ) The spin lock of , Then the thread will be busy looping all the time —— rotate —— wait for Lock is available again . If it's not disputed , The executing thread that requests it gets it immediately and continues . Spinlocks can prevent more than one execution thread from entering the critical area at any time . Sleep characteristics of semaphores , Make semaphores suitable for situations where locks will be held for a long time ; Only in the process The following is used , Because interrupt context cannot be scheduled ; In addition, when the code holds semaphores , No You can hold the spin lock again . Linux The synchronization mechanism in the kernel : Atomic manipulation 、 Semaphore 、 Read and write semaphores and spinlocks API, another Other synchronization mechanisms , Including large kernel locks 、 Read-write lock 、 Big reader lock 、RCU (Read-Copy Update, As the name suggests, it means reading - Copy and modify ), And sequence lock .

2. Linux What is the meaning of user mode and kernel mode in ?

MS-DOS Wait for the operating system in a single CPU Run in mode , But some classes Unix The operating system makes With dual mode , Can effectively achieve time sharing . stay Linux On the machine ,CPU Or in trust Kernel mode of , Or in restricted user mode . Except that the kernel itself is in kernel mode , the Some user processes run in user mode . Kernel mode code has unlimited access to all processor instruction sets as well as all memory and I/O Space . If user mode processes are to have this privilege , It must be sent to the device driver or other through a system call Kernel mode code makes a request . in addition , User mode code allows page faults to occur , And kernel mode Code does not allow . stay 2.4 And earlier kernels , Only user mode processes can be context switched out , From others to Cheng grabs .
Unless two things happen , Otherwise, kernel mode code can always be exclusive CPU: (1) It gave up voluntarily CPU; (2) An interrupt or exception has occurred .
2.6 Kernel introduces kernel preemption , Most kernel mode code can also be preempted .

3. How to apply for large kernel memory ?

stay Linux In the kernel environment , The success rate of large memory application decreases with the increase of system running time , Although it can pass vmalloc Serial calls Request memory with physical discontinuity but continuous virtual address , But, after all, Its use efficiency is not high and in 32 Bit system vmalloc Memory address space is limited . therefore , General The suggestion is to apply for large amount of memory in the system startup phase , But the probability of its success is only relatively high , instead of 100%. If the program really cares about the success of the application , It can only be withdrawn “ Start inside save ”Boot Memory).

The following is a sample code for applying and exporting boot memory :

void* x_bootmem = NULL;
EXPORT_SYMBOL(x_bootmem);
unsigned long x_bootmem_size = 0;
EXPORT_SYMBOL(x_bootmem_size);
static int __init x_bootmem_setup(char *str)
{
x_bootmem_size = memparse(str, &str);
x_bootmem = alloc_bootmem(x_bootmem_size);
printk("Reserved %lu bytes from %p for xn", x_bootmem_size, x_bootmem);
return 1;
}
__setup("x-bootmem=", x_bootmem_setup);

It can be seen that its application is relatively simple , But the pros and cons are always symbiotic , It inevitably has its own limitations : Memory application code can only be connected to the kernel , Cannot be used in modules . The requested memory is not allocated by the page Utensils and slab Distributor usage and statistics , That is, it's outside the system's visible memory , Even in Somewhere in the future you let it go . The average user will only request a large amount of memory , If you need to put it into practice Now complex memory management needs to be implemented by ourselves .

Where memory allocation failure is not allowed , By starting inside Saving and reserving memory space will be our only choice .

4. What are the main ways of user process communication ?

1) The Conduit Pipe): Pipes can be used for communication between processes with kinship , Allow one process and another Communication between processes with which it has a common ancestor

2) name pipes named pipe): Named pipes overcome the limitation that pipes have no names , therefore , In addition to having Besides the functions of the pipeline , It also allows communication between unrelated processes . Named pipes in the file system There is a corresponding file name in . Named pipe through command mkfifo Or system call mkfifo To create .

3) The signal Signal): Signal is a more complex way of communication , Used to notify the receiving process that something has happened raw , Except for interprocess communication , The process can also signal the process itself ;linux In addition to supporting Unix Early signal semantic function sigal Outside , Semantic compliance is also supported Posix.1 Standard signal function sigaction actually , This function is based on BSD Of ,BSD In order to realize reliable signal mechanism , And be able to Unified external interface , use sigaction Function re implemented signal function ).

4) news Message) queue : Message queues are linked tables of messages , Include Posix Message queue system V Message queue . Processes with sufficient privileges can add messages to the queue , Processes that are given read permission are You can read messages in the queue .

5) Message queuing overcomes the lack of signal carrying information , The pipe can only carry no grid There are some shortcomings such as byte stream and limited buffer size

6) Semaphore semaphore): Mainly as a means of synchronization between processes and between different threads of the same process .

7) Socket Socket): More general interprocess communication mechanism , It can be used between processes between different machines signal communication . At first it was by Unix Systematic BSD Branch developed , But now it can be transplanted to other class Unix On the system :Linux and System V Socket is supported in all variants of .

5. What are the functions that apply kernel memory through the partner system ?

In the physical page management, the partner system based on zone is implemented zone based buddy system). For not Memory in the same zone uses a separate partner system (buddy system) management , And independently monitor free pages . Corresponding interface alloc_pages(gfp_mask, order),_ _get_free_pages(gfp_mask, order) etc. .

Supplementary knowledge :

1. Principle that Page global (Page Global Directory) Page middle table of contents (Page Middle Directory) The page global directory contains the addresses of the parent directory of several pages , The upper directory of the page contains several middle directories in turn The address of , The middle directory contains the addresses of several page tables , Each page entry refers to To a page box .

Linux Used in 4KB The size of The page box serves as the standard memory allocation unit . 1.1. Partner system algorithm To avoid this ,Linux The partner system algorithm is introduced into the kernel (buddy system). hold All free page boxes are grouped into 11 individual Block list , Each block list contains a size of 1,2,4,8, 16,32,64,128,256,512 and 1024 Page frame blocks of consecutive page frames . You can apply for 1024 even Continuation box , Corresponding 4MB Size of continuous memory .

The physical address of the first page frame of each page frame block Is an integer multiple of the block size . When the page box block is released , Will take the initiative to merge two consecutive page frame blocks into a larger page frame block . slab The distributor comes from Solaris 2.4 Of Allocation algorithm , Works on physical memory page frame allocator , Manage caching for objects of a specific size , Fast and efficient memory allocation .

2. Common memory allocation functions unsigned long __get_free_pages(gfp_t gfp_mask, unsigned int order) __get_free_pages Function is the most primitive way to allocate memory , Get the original... Directly from the partner system Page box , The return value is the starting address of the first page box .__get_free_pages In implementation, it's just encapsulation 了 alloc_pages Letter Count , From code analysis ,alloc_pages Function will assign a length of 1< struct kmem_cache kmem_cache_create(const char name, size_t size void (ctor)(void, struct kmem_cache , unsigned long), void kmem_cache_alloc(struct kmem_cache *c, gfp_t flags) kmem_cache_create/ kmem_cache_alloc Is based on slab A memory allocation formula of the allocator type , It is suitable for repeated allocation and release of memory blocks of the same size .

First use kmem_cache_create gen Create a cache area , And then use kmem_cache_alloc from This cache area gets the new Memory block .kmem_cache_alloc The maximum amount of memory that can be allocated at a time is determined by mm/slab.c In the document MAX_OBJ_ORDER Macro definition , In the default 2.6.18 In kernel version , The macro is defined as 5, So you can apply at most once 1<<5 * 4KB That is to say 128KB Continuous physical memory of . Analysis of the kernel source code found , kmem_cache_create Functional size Parameter is greater than the 128KB Called when BUG(). Test results verify The results of the analysis , use kmem_cache_create Allocate more than 128KB To crash the kernel .

void *kmalloc(size_t size, gfp_t flags) 2.4.vmalloc The first several memory allocation methods are physically continuous , Can guarantee a lower average access time . But at some On some occasions , Requests for memory areas are not very frequent , Higher memory access time is also Acceptable , this So we can assign a linear continuity , Address of physical discontinuity , The benefit is that it can be distributed at one time Big chunks of memory .

chart 3-1 surface It shows that vmalloc The address range used by the allocated memory .vmalloc Yes There is no clear limit to the amount of memory that can be allocated at a time . For performance reasons , Use with caution vmalloc function . During the test , It can be allocated at one time 1GB Space .

2.5.dma_alloc_coherent ma_addr_t dma_handle, gfp_t gfp) 2.6.ioremap ioremap It's a more direct memory “ Distribute ” The way , When using, directly specify the physical starting address and the need for The size of memory to be allocated , And then put the paragraph The physical address maps to the kernel address space .ioremap be used The physical address space of is determined in advance , And the memory above The distribution is not the same , and It's not allocating a new piece of physical memory .ioremap It is mainly used for device driving , It can make CPU Direct access to Of equipment IO Space .ioremap The amount of memory that can be mapped is determined by the original physical memory space , So no There are tests . If you want to allocate a lot of contiguous physical memory , None of the above allocation functions can be satisfied , You can only use more special Special way , stay Linux Inside Kernel boot phase to reserve some memory . void alloc_bootmem(unsigned long size) 2.7.2. Reserve top memory through kernel boot parameters 3. Comparison of several distributive functions __get_free_pages Operate directly on the page box 4MB It is suitable for allocating a large amount of continuous physical memory kmalloc be based on kmem_cache_alloc Realization 128KB The most common form of distribution , Need to be smaller than the page box Size of memory can be used when dma_alloc_coherent be based on __alloc_pages Realization 4MB Apply to DMA fuck do alloc_bootmem Start up kernel when , Reserve a piece of memory , The kernel is invisible, smaller than the physical memory Small , High memory management requirements .

6. adopt slab The functions used by allocator to request kernel memory are ?

7.Linux How is the kernel space and user space divided ( With 32 Bit system For example )?

8. vmalloc() What are the characteristics of the requested memory ?

9. User program use malloc() What is the range of memory space applied for ?

10. Support and enable MMU In the system ,Linux The kernel and user program are divided into Don't run in physical address mode or virtual address mode ?

11. ARM The processor maps storage space through several levels of tables ?

12. Linux What components are used to support multiple file binding ?

Virtual file system .

13. Linux What are the key data structures of virtual file system ?( At least write four )

struct super_block 
struct inode
struct file
struct dentry;

14. The operation function of a file or device is stored in that data structure ?

struct file_operations

15.Linux What documents are included in ?

 Executable files , Ordinary documents , Directory file , Link files and device files , Pipeline files 

16. What are the system calls to create a process ?

clone(),fork(),vfork(); System call service routine :sys_clone,sys_fork,sys_vfork;

17. call schedule() There are several ways to switch processes ?

1. system call  do_fork(); 
2. Timed interrupt  do_timer(); 
3. Wake-up process  wake_up_process 
4. Change the scheduling policy of the process  setscheduler(); 
5. System call comity  sys_sched_yield(); 

18.Linux Is the scheduler based on the dynamic or static priority of the process To schedule the process ?

Liunx The scheduler schedules a process according to its dynamic priority , But dynamic priorities are It is calculated according to the static priority according to the algorithm , They are two associated values .

Because of the high priority Is always scheduled before the lower priority process , To prevent multiple high priority processes from occupying CPU information Source , Cause other processes to lose possession CPU, So we use the concept of dynamic priority .

19. What is the core data structure of process scheduling ?

struct runqueue, struct task_struct, struct sched_struct

20. How to load 、 Uninstall a module ?

insmod load ,rmmod uninstall

21. What space are the modules and applications running in ?

Modules run in kernel space , The application runs in user space

22.Linux Is floating-point operation implemented by application or kernel ?

Application implementation ,Linux The floating point operation in is realized by using mathematical library functions , Library functions can be applied to Call after program link , Cannot be called by kernel link . These operations are run in applications , however And then feed back the results to the system .

Linux If the kernel has to do floating point operations , You need to build a kernel When you choose math-emu, Use software to simulate floating point operations , It is said that there are two costs to doing so : user You need to rebuild the kernel when you install the driver , It may affect other applications , Make these applications When you do floating point operations, you also use math-emu, Greatly reduced efficiency .

23. Can module programs use linkable library functions ?

Module programs run in kernel space , Cannot link library functions .

24.TLB What is cached in ?

TLB, Page table cache , When a linear address is first converted to a physical address , Put the linear address and the object The corresponding address is placed in TLB in , For the next time you access this linear address , Speed up conversion .

25.Linux What kinds of equipment are there ?

Character devices and block devices . Network card is the exception , It doesn't correspond directly to the device file ,mknod The system call uses To create device files .

26. Which is the key data structure of character device driver ?

Character device descriptor struct cdev,cdev_alloc() For dynamic allocation cdev The descriptor , cdev_add() Used to register a cdev The descriptor ,cdev Contains a struct kobject Type of Data structure it's the core data structure .

27. What functions does the device driver include ?

open(),read(),write(),llseek(),realse();

28. How to uniquely identify a device ?

Linux Use a device number to uniquely identify a device , It is divided into equipment numbers : Main equipment number and number Device number , The general master device number indicates the driver corresponding to the device , The secondary device number corresponds to the device file equipment , Use... In the kernel dev_t To indicate the equipment number , Generally it is 32 Bit length , among 12 Bit use Indicates the main equipment number ,20 Bits are used to indicate the secondary device number , utilize MKDEV(int major,int minor); Used to generate a dev_t Object of type .

29.Linux How to implement system call ?

Realized by software interruption , First , The user program sets the parameters for the system call , One of the numbers is the system Call number , After setting the parameters , Program execution system call instructions ,x86 There are some soft interrupts on int Produced , This command causes an exception , Produce an event , This event causes the processor to jump Go to kernel mode and jump to a new address . And start processing the exception handler there , The anomaly at this time Processing is the system call program .

30.Linux What is the role of soft interrupts and work queues ?

Linux Soft interrupts and work queues in are interrupt handling .

1. Soft interrupts are usually “ Delay function ” The general term of , It can't sleep , Can't block , It's on the break Below , You can't switch into the city , Soft interrupts cannot be interrupted by themselves , Can only be interrupted by hardware interrupt ( Upper half ), Can run concurrently on multiple CPU On . So soft interrupts must be designed as reentrant functions , So we need to To spin lock to protect its data structure .

2. The function in the work queue is in the process context , It can sleep , It can also be blocked , Can be different in Switch between processes . Different jobs have been done . Neither delayable functions nor work queues can access the user's process space , Delayable functions are not possible at execution time There are any running processes , The function of work queue is executed by kernel process , He can't access the user space address .

image
Click on Go straight in and share your learning materials
Related video recommendation :
【linux The server 】 First time to know Linux Kernel process communication can play like this \( On \)
【linux The server 】 First time to know Linux Kernel process communication can play like this \( in \)
【linux The server 】 First time to know Linux Kernel process communication can play like this \( Next \)

版权声明
本文为[Deep Linux]所创,转载请带上原文链接,感谢

Scroll to Top