
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/io.h>
#include <sys/time.h>

#define BASEPORT 0x3da

void vgasync_cleanup( void )
{
    fprintf( stderr, "vgasync: Cleaning up.\n" );
    if( ioperm( BASEPORT, 1, 0 ) ) {
        perror( "ioperm" );
        exit( 1 );
    }
}

void vgasync_init( void )
{
    atexit( vgasync_cleanup );

    /* Get access to the ports */
    if( ioperm( BASEPORT, 1, 1 ) ) {
        perror( "ioperm" );
        exit( 1 );
    }
}

void vgasync_spin_while_refresh( void )
{
    /* TODO: A better timeout. */
    int i = 0x00ffffff;

    for(;i;--i) {
        /* wait for the refresh to occur. */
        if( (inb( BASEPORT ) & 8) ) break;
    }
    /* now we're inside the refresh */
    for(;i;--i) {
        /* wait for the refresh to stop. */
        if( !(inb( BASEPORT ) & 8) ) break;
    }

    if( !i ) fprintf( stderr, "vgasync: Timeout hit.\n" );
}

