#include        "defs.h"

HANDLE  g_hMutex;

void    init_lock(){
        NTSTATUS        status;
        OBJECT_ATTRIBUTES oa;
        
        InitializeObjectAttributes(&oa, NULL, OBJ_CASE_INSENSITIVE, NULL, NULL);
        status = NtCreateMutant(&g_hMutex,
                                MUTEX_ALL_ACCESS,
                                &oa,
                                FALSE);
}
                                        
void    acquire_lock(){
        NtWaitForSingleObject(g_hMutex, FALSE, NULL);
}

void    release_lock(){
        NtReleaseMutant(g_hMutex, NULL);
}

void    init_spin_lock(__in lock_t *lock){
        memset(lock, 0, sizeof(lock_t));
}

void    acquire_spin_lock(__in lock_t *lock){
        unsigned int tid;
        LARGE_INTEGER   delay;
        
        lock_t       *plock = lock;
        tid = get_currentthreadid();
        if (lock->tid == tid) return;
        
        
//        __asm
//        {
//                mov     ecx, plock
//                mov     eax, 1
//__spin:                
//                xchg    dword ptr[ecx+4], eax
//                test    eax, eax
//                jz      __lock_acquired
//                pause
//                jmp     __spin
//__lock_acquired:
//        }                       
        while (_InterlockedExchange(&lock->lock, 1) == 1)
                NtYieldExecution();
        lock->tid = tid;     
}


void    release_spin_lock(__in lock_t *lock){
        _InterlockedExchange(&lock->tid, 0);
        _InterlockedExchange(&lock->lock, 0);     
}

void    wait_zero(__in unsigned long volatile *lock){
        while (*lock != 0)
                NtYieldExecution();       
}