Concurrent competing states (semaphores and spin locks)
Code transfer to concurrent competition control
An example of competition caused by concurrent processes
The character drivers mentioned above are not considering the concurrency status. Imagine
One process reads one character device, and another process writes data to the device at the same time (this is the case)
The original device contains a B c d. If you want the device to write 1 2 3 4, read and write one byte at a time
| T1 |
T2 |
T3 |
T4 |
T5 |
T6 |
T7 |
T8 |
| R |
W |
W |
R |
W |
R |
R |
W |
| A |
1 |
2 |
2 |
3 |
3 |
D |
4 |
R: Read
W: Write
So we finally read that a23d is not the original ABCD.
If two processes write data to a device at the same time, the value written to the device may not be what the process wants or what the B Process wants.
Concurrency and Competition
Concurrency means that multiple processes simultaneously access the same piece of code (not limited to the Code in the kernel space)
A race state is the result of access to shared resources. Concurrent Processes access the same data or structure (hardware resources.
There are two main ideas for solving the competition
1. All codes do not use global variables.
2. Use the lock mechanism to ensure that only one process uses shared resources at a time.
Obviously, the first method is impossible. We can only use global variables as few as possible, instead of completely avoiding them.
The following describes two lock mechanisms.
Semaphores
This concept should not be very unfamiliar to us. At least we have heard of it. It has two types of operations: P operation and V operation.
Processes that want to enter the critical section call the P operation to detect the current semaphore. If the semaphore is greater than 0, the semaphore is reduced by 1 to enter the critical section. Otherwise, the process waits for other processes to release the semaphore, the release of a semaphore increases the semaphore value through a V operation. In some cases, it will wake up the process waiting for this semaphore.
The term "critical section" is simply the code for internal operations on shared data.
Implementation of semaphores in Linux Kernel
Since the lld3 (2.6.10) version has changed a lot in (3.1) kernel functions, the functions described in many books no longer exist, after several versions of the new kernel, the functions I mentioned will also change.
The semaphore structure and related functions are defined in <Linux/semaphore. h>.
Create semaphores
void sema_init(struct semaphore *sem, int val)
SEM: semaphore struct
VAL: the initial semaphore value (indicating the number of resources). When Val is set to 1, it indicates that the Code allows only one process to access at the same time. This is called a mutex lock]
void init_MUTEX();void init_MUTEX_LOCKED();
Two functions defining mutex locks (these two functions are no longer available in the latest kernel, so do not use them)
struct simple_dev{char *data;loff_t count;struct cdev cdev;struct semaphore semp;};static __init int simple_init(void){...for( index = 0 ; index < DEV_COUNT ; ++index ){sema_init(&char5_dev[index].semp,1);//init_MUTEX(&(char5_dev[index].semp));init_waitqueue_head(&(char5_dev[index].queue));}...}
P operation
void down(struct semaphore *sem);int __must_check down_interruptible(struct semaphore *sem);int __must_check down_killable(struct semaphore *sem);int __must_check down_trylock(struct semaphore *sem);int __must_check down_timeout(struct semaphore *sem, long jiffies)
When the semaphore value is greater than 0, the first function directly reduces the semaphore value by one program to continue running, when the semaphore is 0, the process will be awakened only when other processes release the semaphore (not recommended)
The second function is based on the first operation. If the process does not get the semaphore sleep, it will be awakened when other processes release the semaphore or initiate an interruption, -eintr is returned when the interrupted signal is awakened, and 0 is returned if the call succeeds.
The third function can call this function if no other task obtains this semaphore. When receiving the interrupt signal, it returns-eintr.
The fourth function tries to get the semaphore. It does not sleep when it cannot be obtained. Instead, it continues to run. If it returns 0, it indicates that the semaphore is obtained. If it returns 1, it indicates that it cannot be obtained.
The fifth function can set the maximum sleep time, but this function cannot be interrupted.
V Operation
void up(struct semaphore *sem)
This operation first detects other processes waiting for this semaphore. If yes, it will wake up the process without changing the semaphore value. If not, it will add 1 to the semaphore value.
Static ssize_t simple_read (struct file * filp, char _ User * userstr, size_t count, loff_t * Loff) {struct simple_dev * Dev = NULL; int data_remain = 0; int err; D ("[% s:] In % s \ n", current-> comm, _ FUNC _); Dev = filp-> private_data; err = down_interruptible (& Dev-> SEMP); If (ERR) {If (ERR =-eintr) War ("return by an interrupt signal \ n "); elseprintk (kern_err "an error occured in down_interruptible \ n"); Return err;} else {d ("have get the mutex % d \ n ", _ line __);} /*************************************** ********************************* * **********/up (& Dev-> SEMP ); return count ;}
Spin lock
The spin lock is another lock mechanism, and the semaphore will cause the process to sleep. In the code that cannot sleep, we need to use the spin lock.
Spin locks are also mutually exclusive. There are two operations: "Lock" and "unlock". When the program needs to lock, it first checks whether the lock is available. If it is available, it obtains the lock, the program enters the critical section. Otherwise, it enters the busy waiting period to repeatedly check whether the lock is available (this is the spin). If the code operation in the critical section is completed, it is unlocked.
The spin lock mechanism is also used in the implementation of semaphores (if you are interested, check the kernel source code and do not expand it here. We will introduce it later when writing the kernel)
Because the spin lock will "Spin" when the lock is not available, so the execution speed of our critical section should be as fast as possible, it is best to use atomic operations (not sleep ). This is also the core rule for using spin locks. In most cases, we cannot do this, so spin locks are not used frequently in the driver as well as semaphores.
Initialization
spin_lock_init(_lock)
Lock
static inline void spin_lock(spinlock_t *lock)static inline int spin_trylock(spinlock_t *lock)static inline void spin_lock_irq(spinlock_t *lock)spin_lock_irqsave(lock, flags)static inline void spin_lock_bh(spinlock_t *lock)
The first function is to directly lock without interrupting
The second function will try to lock and check whether the returned result is locked. The program continues to run when it cannot be locked.
The third function disables interruption and does not save the original interruption status.
The fourth function saves the original interrupt state before stopping the interrupt,
The fifth function indicates that only software interruption is prohibited and hardware interruption is enabled.
Because the spin lock will not be interrupted in essence, we recommend that you use a function that contains a function to prohibit interruption.
Unlock
static inline void spin_unlock(spinlock_t *lock) //static inline void spin_unlock(spinlock_t *lock)static inline void spin_unlock_irq(spinlock_t *lock)static inline void spin_unlock_irqrestore(spinlock_t *lock, unsigned long flags)static inline void spin_unlock_bh(spinlock_t *lock)
It corresponds to the five locked functions, which are unlocked separately (corresponding to the second locked operation, which must be unlocked using the spin_unlock when the lock is successful)
Deadlock
The above only mentions the advantages of using locks and how to use locks, but the introduction of the lock mechanism also brings risks, that is, deadlocks. The most obvious manifestation of a process deadlock is that it crashes.
As shown in, process a occupies lock 1 and requires the lock 2 program to continue when holding the lock 1.
Process B occupies the lock 2, and obtains the lock 1 program while holding the lock 2 to continue running. In this way, process a and process B are stuck here, so they do not interact with each other, this leads to a deadlock.
Or try to get the same lock in a process at the same time.
Glossary of deadlock
Two or more processes are waiting for each other due to resource competition during execution. If there is no external force, they will not be able to proceed. In this case, the system is in a deadlock state or the system has a deadlock.
Solution to the deadlock:
1. The order of adding and unlocking is consistent.
When multiple locks are required, they should always be obtained in the same order, and it is best to unlock them in reverse order.
2. Use atomic variables
Atomic variables are not operated concurrently by multiple processes. The Kernel provides an atomic type (in atomic_t <ASM/stomic. h>)
3. Set the lock timeout value
If the lock cannot be obtained within a certain period of time, give up and release the occupied lock.