spinlock implementation with arm

ARM 323浏览

1      ARCH_SPIN_LOCK /UNLOCK

Take armv7 code for example, its codes is much clear and easy tounderstand

Codes 

static inline void arch_spin_lock(arch_spinlock_t *lock)

{

        unsigned long tmp;

        u32 newval;

        arch_spinlock_tlockval;

 

        __asm__ __volatile__(

"1:     ldrex   %0, [%3]n"     //lockval=  lock->slock

"       add     %1, %0, %4n"   //newval  = (lockval->next+1) | lockval->owner

"       strex  %2, %1, [%3]n" //lock->slock =newval

"       teq     %2, #0n"

"       bne     1b"             //if status is not 0 means storehasn't took place

        : "=&r"(lockval), "=&r" (newval), "=&r" (tmp)

        : "r"(&lock->slock), "I" (1 << TICKET_SHIFT)

        : "cc");

 

        while(lockval.tickets.next != lockval.tickets.owner) { //old value get it from Line81

                wfe();

               lockval.tickets.owner = ACCESS_ONCE(lock->tickets.owner);

        }  

 

        smp_mb();      

Description:

      arch_spin_lock:

    lock_op1: save lock tolockval and increase next of lock

lock_op2:if lockval.next == lockval.owner

         a) yes, then get lock and exit

                b) no, wfe

    lock_op3: exit from wfe , setlockval->owner to lock->owner and go to op2

   

    arch_spin_unlock:

    unlock_op1: increase ownerof lock

    unlock_op2: sev to wakeupwfe

   

    Example1: two processes acquirespin lock, assume next = owner = n at the beginning

    process 1:                                      
 process 2:

    arch_spin_lock:                            arch_spin_lock:

    lock_op1:lockval(next=owner=n), lock(next=n+1, owner=n)

                                                              
lock_op1:lockval(next=n+1, owner=n), lock(next=n+2, owner=n)

lock_op2: lockval (next == owner), get lock        

lock_op2: wfe

   

    arch_spin_unlock:

    unlock_op1: lock(next=n+1,owner=n+1)

                                                       
lock_op3: exit and lockval(next=n+1, owner=n+1)

                                                      
lock_op2: lockval(next=owner=n+1), lock(next=n+2, owner=n+1)

   

                                                       
arch_spin_unlock:

                                                       
unlock_op1: lock(next=n+2, owner=n+2)

                                                           
unlock_op2:set wakeup event

 

将arch_spin_lock/unlcok的过程 类比为去只有一张桌子的餐厅排队吃饭:

Spin_lock: 排队取号 next, 并将next加1做为下一个排队者的号

可以使用桌子餐厅吃饭的号(临界资源):                 Owner

Spin_lock:吃好了, 将 owner 加1作为下一个可以餐厅吃饭的号

Spin_lock:

a)     排队取号next,即自己什么时候可以餐厅吃饭;

b)     将下一张号加一next ++( 别人接下来取的号)

c)      看看自己的号的next和可以餐厅吃饭的号owner是不是相等,是则表示自己可以使用桌子吃饭,否则则等待

Spin_unlock:

                饭吃好了,把owner+1,表示现在谁可以使用桌子吃饭。广播通知,谁可以吃饭了,大家看看自己可以吃饭的号owner是不是自己的号next,是则进去吃饭,否则继续等待。

 

Summarize as below:

Arch_spin_lock和arch_spin_unlock不配对的话:owner和next肯定是不相等的。

Next-owner=1: 通常表示有人在访问临界资源

Next-owner>1:表示多个人访问临界支援,产生竞争。