Venkatesh
Venkatesh

Reputation: 157

How can we know we are inside a spinlock?

I have a function which is called by multiple functions. Some functions call it with spinlock held and some without any lock. How can I know if my function is called with spinlock held?

I have a big piece of code written some time back. It has some functions which are called with and without locks from different code paths. The functions allocate skbs with GFP_KERNEL flag only considering the cases without locks. It is causing issues when called with spin_lock(). I need to handle both the cases to avoid sleeping inside a spin_lock.

Upvotes: 0

Views: 445

Answers (2)

Venkatesh
Venkatesh

Reputation: 157

I need to check only preemption disabled or irqs disabled. Based on that I can allocate memory with GFP_KERNEL or GFP_ATOMIC. Hence I don't need to rely on when spin_lock or another lock. Using in_atomic() and irqs_disabled() functions, I can achieve it. Thanks

Upvotes: 0

nos
nos

Reputation: 229108

How can I know if my function is called with spinlock held?

You cannot, not directly. You would need to set a flag in some structure yourself that indicates whether you hold the lock or not.

You are better off creating 2 functions. One that you call if you hold the lock, one that you call if you don't hold the lock.

//b->lck must be taken
void foo_unlocked(struct bar *b)
{
    //do your thing, assume relevant lock is held
}

//b->lck must not be taken
void foo(struct bar *b)
{
    spin_lock(b->lck);
    foo_unlocked(b);
    spin_unlock(b->lck);
}

Upvotes: 5

Related Questions