Linux Kernel Analysis notes-kernel Synchronization

Source: Internet
Author: User

Kernel synchronization involves a lot of things, so I am not very embarrassed. Let's talk about some concepts first, and then the method.

Synchronization is to avoid concurrency and prevent competition conditions. I will not give an example of the critical section, but I will have it in any operating system book. The proposal of the lock mechanism also solves some problems. We will talk about it later, as long as we know that the use of the lock is voluntary and not mandatory. Linux also provides several different lock mechanisms. The main difference is that when the lock is contention, some will simply execute the wait, and some locks will make the current task sleep until the lock is available, this is detailed later. The real difficulty lies in discovering and identifying the data to be shared and the corresponding sharing zone. First, let's talk about some Sensibility: Most kernel data structures need to be locked. If other execution threads can access the data, add some form of lock to the data. If anything else can see it, lock it. In short, almost all kernel global variables and shared data require some form of synchronization. For details about the lock, make sure to obtain the lock in the same order when nesting the lock. Do not repeatedly request the same lock. When releasing the lock, it is best to release the lock in the reverse order of obtaining the lock. The lock granularity is used to describe the data size of lock protection. Next we will discuss the real synchronization method:

1. atomic operation. An operation that is not interrupted during execution is a command that cannot be separated. This Linux Kernel provides two sets of atomic operation interfaces: Atomic Integer Operation and atomic bit operation. Well, let's talk about the atomic Integer Operation first. Atomic operations on integers can only process atomic_t data. It must be noted that, although the integer data on all machines supported by Linux is 32-bitCodeThis type of data can only be used as 24 bits. Declarations required for atomic operations are in ASM/Atomic. h. The atomic Integer Operation list is as follows;

When writing code and using atomic operations, try not to use complicated locking mechanisms, because in most or 100% cases, atomic operations are more complex than synchronization methods, the cost to the system is small, and the impact on the cache-line is also small.

Corresponding to atomic integer operations, there is also an atomic operation, which is related to the architecture, defined in the file <ASM/bitops. h>, which operates on common memory addresses. Its parameter is a pointer and a single digit, and The 0th bit is the lowest valid bit of the given address. There is no data structure like atomic_t here, as long as the Pointer Points to any desired data, you can operate. The list of atomic bit operation functions is as follows:

At the same time, the kernel also provides a set of non-atomic functions corresponding to the preceding operations. The operations are identical. The difference is that they do not guarantee atomicity and the name prefix has two underscores, for example, the non-atomic form corresponding to test_bit () is _ test_bit (). if atomic operations are not required, these functions may be executed more efficiently. The kernel also provides two functions to search for the first set (or unset) bit from the specified address:

 
Int find_first_bit (unsigned long * ADDR, unsigned int size); int find_first_zero_bit (unsigned long * ADDR, unsigned int size );

The first parameter is a pointer, and the second parameter is the total number of digits to be searched. The returned values are the bits of the first (or not set) bit. If the search scope is limited to one word, it is better to use the _ FFs () and _ ffz () functions. They only need to specify an address to be searched as a parameter.

2. spin lock. The critical section is far less simple than we think, and sometimes it may span multiple functions. Spin locks are the most common locks in Linux kernel. If an execution thread tries to obtain a contention (held) spin lock, the thread will keep repeating-Rotating-waiting for the lock to be available again. The same lock can be used in multiple locations. For example, access to a given data can be protected and synchronized. The above spin process is very time-consuming, so the spin lock should not be held for a long time. The front side can also sleep the request thread, and the CPU can execute other code until the lock is available to wake it up, but the spin lock occupies the CPU due to waiting. The above hibernation process also brings about overhead of context switching. Therefore, it is better to hold the spin lock for a time less than the time for completing two context switches. The implementation of spin locks is closely related to the architecture, and the code is often implemented by assembly. The components related to the architecture are defined in <ASM/spinlock. h>. The interface is defined in the file <Linux/spinlock. h>. The spin lock operation list is as follows:

The spin lock is only used as a switch that is enabled when the kernel preemption mechanism is set. If kernel preemption is prohibited, the spin lock will be completely removed from the kernel during compilation. In addition, the spin locks implemented by the Linux kernel cannot be recursive. The spin lock is used for interrupt processing.Program). When using a spin lock in the interrupt handler, you must disable local interruption before obtaining the lock (Interrupt requests on the current processor ). Otherwise, the interrupt handler interrupts the kernel code that is holding the lock and may try to compete for the held spin lock. In this way, the interrupt handler will spin. But the lock holder cannot run before the interrupt handler is executed. This is a double request deadlock. Note that all you need to disable is the interruption on the current processor. If the interruption occurs on different processors, even if the interrupt handler spin on the same lock, it does not prevent the lock owner (on different processors) from eventually releasing the lock. The last two functions, spin_lock_bh (), are used to obtain the specified lock. At the same time, they disable the execution of all lower half. The corresponding spin_unlock_bh () function executes the opposite operation. Finally, pay attention to the relationship between the spin lock and the lower half.

3. read-write spin lock. Sometimes, the purpose of a lock can be clearly divided into read and write. When an operation on a data structure can be divided into two types: read and write, you can use the read-write spin lock mentioned here. This mechanism provides different locks for reading and writing respectively. One or more read tasks can hold reader locks concurrently, while write locks can only be held by one write task, and concurrent read is not allowed at this time. The list of operation functions is as follows:

In fact, it is safe even if a thread recursively acquires the same read lock. In other words, we should be able to clearly distinguish between reading and writing before using it. If there are only read operations but no write operations in the interrupt processing program, you can use the "interrupt prohibition" lock in combination and use read_lock () instead of read_lock_irqsave () to protect the read. However, you still need to use write_lock_irqsave () to prohibit the interruption of write operations. Otherwise, the read operation in the interrupt may be locked to the write lock (if the reader is performing an operation, the read locks are released because the read locks are not all released, so the write operation will spin, and the read operation can only continue after the return of the interrupt that contains the write operation, releasing the read lock, the deadlock occurs ). Finally, it should be noted that this mechanism is biased towards the read lock: When the read lock is held, the write operation can only wait for mutex access, but the reader can continue to successfully occupy the lock. The spin wait writer cannot obtain the lock before all the read locks release the lock. Therefore, a large number of readers will make the suspended writers hungry.

4. semaphores. It is a sleep lock and its implementation is related to the architecture, defined in <ASM/semaphore. h>. If a task tries to obtain an occupied semaphore, the semaphore will push it into a waiting queue and then let it sleep. At this time, the processor will regain freedom to execute other code. When the process holding the semaphore releases the semaphore, the task in the waiting queue will be awakened and the semaphore will be obtained. If you need to make a choice in the spin lock and semaphore, you should make a judgment based on the length of time the lock is held. If the lock is not long and the code will not sleep, using the spin lock is the best choice. On the contrary, if the lock may take a long time or the Code may sleep when holding the lock, it is best to use semaphores to complete the lock function. A useful feature of semaphores is that it allows any number of lock holders at the same time, while a spin lock allows a task to hold it at most at a time. The number of holders allowed by semaphores at the same time can be specified when the semaphores are declared. When the semaphores are set to 1, they become mutex semaphores; otherwise, they become Count semaphores. The list of operation functions is as follows:

The semaphore supports PV operations.

5. read-write semaphore. The relationship between this and semaphores is the same as that between spin locks and read/write spin locks, represented by the rw_semaphore structure. Defined in Linux/rwsem. h. All read/write semaphores are mutex semaphores. Operation functions include:

 
Declare_rwsem (name) // declare a read/write semaphore named name and initialize it. Void init_rwsem (struct rw_semaphore * SEM); // initializes the read/write semaphores SEM. Void down_read (struct rw_semaphore * SEM); // The Reader obtains the SEM. If no SEM is obtained, the caller waits for sleep. Void up_read (struct rw_semaphore * SEM); // The Reader releases the SEM. Int down_read_trylock (struct rw_semaphore * SEM); // The Reader attempts to obtain Sem. If 1 is returned, 0 is returned If no result is returned. It can be used in the interrupt context. Void down_write (struct rw_semaphore * SEM); // The writer obtains the SEM. If no SEM is obtained, the caller waits for sleep. Int down_write_trylock (struct rw_semaphore * SEM); // The writer tries to obtain Sem. If 1 is returned, 0 is returned If no result is returned. Void up_write (struct rw_semaphore * SEM) can be used in the interrupt context; // The writer releases the SEM. Void downgrade_write (struct rw_semaphore * SEM); // downgrade the writer to a reader.

In fact, the above is divided into two categories: semaphores and spin locks. The comparison is as follows:

6. Complete the variable. If a task in the kernel needs to send a signal to notify another task of a specific event, using the complete variables is a simple way to synchronize the two tasks. If a task needs to execute some work, the other task will wait on the completion volume. After the task completes work, it will use the completion variable to wake up the waiting task, just like a semaphore, they have the same idea. They only provide a simple solution to replace semaphores. It has the structure completion, which is defined in Linux/completion. h. The operation interface list is as follows:

Generally, variables are created dynamically as a data structure. The kernel code that completes variable initialization calls wait_for_completion () to wait. After initialization, the initialization function calls completion () to wake up the waiting kernel task.

7. BKL (large kernel lock ). It is a global spin lock that has been around for a long time. It is mainly used to facilitate the implementation of the excessive fine-grained locking mechanism from the initial SMP in Linux. The interesting features are as follows:

1. The task holding BKL can sleep. When a task cannot be scheduled, the lock is automatically discarded and the lock is automatically discarded. When the task is scheduled, the lock is re-obtained. Of course, this is not
When a task holds BKL, sleep is safe. This is just to do so, because sleep will not cause a deadlock in the task.
2. BKL is a recursive lock. A process can request a lock Multiple times without deadlock like a spin lock.
3. BKL can be in the context of a process.
4. BKL is harmful.

Don't be surprised that this mechanism almost does not exist in the kernel and is not encouraged. This idea and interface are mentioned here to meet your needs? The list of Operation interfaces (Linux/smp_lock.h) is as follows:

When BKL is held, kernel preemption is also prohibited. In most cases, BKL is more like protecting code than data.

8. seq lock. This lock provides a simple mechanism for reading and writing shared data. To implement this lock, a Sequence Counter is primarily used. When data is written, a lock is obtained and the sequence value increases. Before and after reading data, the serial number is read. If the read serial number value is the same, it indicates that the read operation has not been interrupted by the write operation. In addition, if the read value is an even number, it indicates that the write operation has not occurred (you must understand that because the initial value of the lock is 0, the write lock will make the value odd and change to even when it is released ). The operation interface is as follows:

Seqlock_t mr_seq_lock = seqlock_unlocked; // defines the sequence lock write_seqlock (& mr_seq_lock); // write operation code block... Write_sequnlock (& mr_seq_lock );

This is similar to normal spin locks. When reading a message in different cases, the write spin locks are very different:

 
Unsigned long seq; do {seq = read_seqbegin (& my_seq_lock);} while (read_seqretry (& my_seq_lock, SEQ ));

When multiple readers and a few readers share a lock, seq locks help provide a very lightweight and scalable look. However, the seq lock is more advantageous to the writer. Only when there are no other writers, write locks can always be obtained successfully. The reader will not affect the write lock, which is the same as the read/write spin lock and semaphore. In addition, the suspended writer keeps making the read operation cycle, knowing that there is no writer lock holding the lock.

9. preemption prohibited: the actual situation is like this. Sometimes we do not need to lock, but do not want the process to preemption (kernel preemption) to modify some data. In this case, we need to disable kernel preemption. You can use preempt_disable () to disable kernel preemption. In this case, a function that can be nested and called can be used any time. Each call must have a corresponding preempt_enable () call. kernel preemption is enabled only when the last preempt_enable () call is called. The kernel preemption operations are as follows:

The preemption technology stores the number of locks held and the number of preempt_disable () calls. When the count is 0, the kernel can be preemptible. Otherwise, no. To solve data access problems on each processor in a more concise way, you can get the processor number through get_cpu () (assuming that the number is used to index the data of each processor ). This function will first disable kernel preemption before returning the current processor Number:

 
Int CPU = get_cpu ();... operate put_cpu () on the data of each processor ();

10. barrier. When dealing with synchronization between multiple processors or between hardware devices, you sometimes need to issue read memory (write) and write memory (storage) commands in the specified order in the program code. When interacting with hardware, you must always ensure that a given read operation occurs before other read or write operations. In addition, on a multi-processor, you may need to read data in the order of writing data (usually ensure that the data is read in the same order ). However, to improve the efficiency, the compiler and processor may re-sort the read and write operations, which is undoubtedly complicated. Fortunately, all processors that may be reordered and written provide machine commands to ensure order requirements. It can also instruct the compiler not to re-sort the command sequences around the specified point. These commands that ensure the order are called barriers. The following lists the memory and compilation barriers methods:

Finally, it is explained that the actual effect of the barrier on different architectures varies greatly. However, the appropriate memory barrier should be used in the worst case so that the code can be optimized for the architecture during compilation.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.