Reputation: 205
I am reading some code and I saw in function foo:
// x is a global variable shared by all functions
spin_lock(&x);
if(some condition)
function();
spin_unlock(&x);
in function();
// do stuff
spin_lock_irqsave(&x, vals);
....
Wouldn't there be a deadlock if "some condition" is true? It seems too obvious so I thought maybe I am missing something?
Thanks
Edit: The code is not part of linux, it is just some random code I found online
Upvotes: 1
Views: 6654
Reputation: 179717
Spin locks are not recursive, and probably never will be since they are intended to be high-performance locks.
Therefore, the code as posted will deadlock if the condition is true.
Upvotes: 1
Reputation: 23266
This code will deadlock (assuming no recursive locking and that this is some Linux kernel code). Usually the irq versions of spin_lock are used when you want to protect your code from being preempted by an interrupt.
The reason for vals is to save the current interrupt state and restore it when calling irqrestore. This is to avoid turning interrupts on prematurely if grabbing multiple spin locks or being in a block where interrupts are disabled.
Upvotes: 1
Reputation: 37262
It would depend on how spin_lock()
and spin_lock_irqsave()
have been implemented.
For example, it's possible that they determine if the lock was already locked by the same CPU and increment a counter if it is; then (when the lock is released) decrement the counter and only release the lock if the counter becomes zero. That way the same CPU could acquire the lock multiple times and it wouldn't cause deadlocks.
It would also be possible for spin_lock_irqsave()
to be something that only disables IRQs, that doesn't actually acquire the lock (e.g. something that assumes/expects spin_lock()
to have been called beforehand). In this case, the lock &x
may just be a convenient place to store/track the fact that IRQs were/are disabled (and maybe spin_unlock()
checks some flag and enables IRQs again if they were disabled).
However, I can't think of a reason for spin_lock_irqsave()
to need a second parameter (vals
).
Another possibility is that the names of these functions are misleading and have nothing to do with what they actually do at all. For example; the spin_lock()
function might order a pizza and the spin_lock_irqsave()
function might display football results.
Basically, there's no information about these functions other than their names, and therefore it's impossible to determine what they do (or if there is or isn't a deadlock).
Upvotes: 0