Spin lock implementation and interrupts
Posted: Sat Jan 09, 2021 7:51 am
I'm making a big presumption on how spin locks should be implemented. Some of that is based on experience, I didn't have a reliable way of synchronising between a driver and its interrupt handlers, as my first spin lock implementation didn't disable interrupts and I'd deadlock when an interrupt handler tried to lock a spin lock already held by the interrupted code.thewrongchristian wrote:If you're pre-empting code that has a spin lock, you're doing it wrong whether you're on UP or MP.nexos wrote:Using a spinlock on a uniproccesser is one of the worst performace decisions out there. For example, T1 acquires a spinlock and gets preempted by T2 while that holding spinlock. T2 then acquires that same spinlock and sitsin its whole timeslice looping. For the timer counter, it would just be better to have a per CPU timer. I think we just got waay off topic.Ethin wrote:You need to send the EOI in the interrupt routine, not when your loading the LDT/IDT. So you'd send the EOI right after incrementing the tick counter.
Also, just a side note: you may wish to turn that tick counter into an atomic integer, especially once you get to SMP. Better to do it earlier than later though. (That's my Rust background speaking, but its generally good to use mutex/locks/atomics on static mutable variables if possible. You can wait though if you don't know how.)
I get nervous about even calling other functions with a spin lock held, and anything protected by a spin lock should be held for the minimal amount of time. I spin lock my scheduler, device driver structures that need to communicate with interrupt handlers, and higher level synchronisation structures like mutexes, which maintain wait lists. Everything else uses the higher primitives built on top of spin locks.
And while you hold the spin lock, you should also disable interrupts, to prevent an interrupt handler also trying to get that spin lock, further reinforcing the notion that spin locks should be help for the minimal amount of time.
Looking through the forums, spin locks tend to be advised to be used with interrupts disabled.
But looking at the Spinlock wiki page, no mention is made of interrupts.
Is this a hole in the wiki page?