#include <stdint.h>

#define CLI __asm__ __volatile__( "cli" )
#define STI __asm__ __volatile__( "sti" )

class spin_lock
{
public:
	spin_lock() : _isr_state{0}, _lock{0} {};

	void lock( void )
	{
		/* remember the current IF flag and disable interrupts */
		_isr_state = ( processor::core::read_eflags() & ( 1 << 9 ) );
		CLI;

		/* go for the lock */
		do {} while( __sync_lock_test_and_set( &_lock, 1 ) );
	}

	void unlock( void )
	{
		/* release the lock */
		__sync_lock_release( &_lock );

		if( _isr_state )
		{
			/* if IF was set re-enable interrupts */
			STI;
		}
	}

private:
	bool             _isr_state = 0;
	volatile uint8_t _lock = 0;
};
