/*
 * $ZEL$
 */

#define _GNU_SOURCE

#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/ioctl.h>

#include "../dev/pci/sis1100_var.h"

static int
read_eprom(int p)
{
    int res=0, i;
    u_int16_t data[0x2c];
    struct sis1100_eeprom_req eeprom_req;
    u_int32_t val;

    eeprom_req.num=0x2c;
    eeprom_req.data=data;
    eeprom_req.addr=0;
    res=ioctl(p, SIS1100_READ_EEPROM, &eeprom_req);
    if (res<0) {
        printf("ioctl(READ_EEPROM): %s\n", strerror(errno));
        return -1;
    }
    for (i=0; i<0x2c; i+=1) {
        printf("0x%02x: %04x\n", i*2, data[i]);
    }

    val=(data[0x24]<<16)|data[0x25];
    printf("LAS1RR: 0x%08x\n", val);
    return 0;
}

static int
write_eprom(int p)
{
    int res=0;
    u_int16_t data[2];
    struct sis1100_eeprom_req eeprom_req;
    u_int32_t val;

    val=0xfff00000;
    data[0]=(val>>16)&0xffff;
    data[1]=(val)&0xffff;

    eeprom_req.num=2;
    eeprom_req.data=data;
    eeprom_req.addr=0x24;
    res=ioctl(p, SIS1100_WRITE_EEPROM, &eeprom_req);
    if (res<0) {
        printf("ioctl(WRITE_EEPROM): %s\n", strerror(errno));
        return -1;
    }
    return 0;
}

static int
patch_eprom(int p)
{
    int res=0;
    u_int16_t data[0x2c];
    struct sis1100_eeprom_req eeprom_req;
    u_int32_t val;

    eeprom_req.num=0x2c;
    eeprom_req.data=data;
    eeprom_req.addr=0;
    res=ioctl(p, SIS1100_READ_EEPROM, &eeprom_req);
    if (res<0) {
        printf("ioctl(READ_EEPROM): %s\n", strerror(errno));
        return -1;
    }

    val=0xfff00000;
    data[24]=(val>>16)&0xffff;
    data[25]=(val)&0xffff;

    eeprom_req.num=0x2c;
    eeprom_req.data=data;
    eeprom_req.addr=0;
    res=ioctl(p, SIS1100_WRITE_EEPROM, &eeprom_req);
    if (res<0) {
        printf("ioctl(WRITE_EEPROM): %s\n", strerror(errno));
        return -1;
    }

    return 0;
}

int main(int argc, char* argv[])
{
    int p;
    printf("\n==== SIS1100 EEPROM Test; V0.1 ====\n\n");

    if (argc!=2) {
        printf("usage: %s pathname\n", argv[0]);
        return 1;
    }

    p=open(argv[1], O_RDWR, 0);
    if (p<0) {
        printf("open \"%s\": %s\n", argv[1], strerror(errno));
        return 1;
    }

    if (read_eprom(p)<0) return 2;
    if (write_eprom(p)<0) return 3;
/*
    if (read_eprom(p)<0) return 4;
    patch_eprom(p);
*/

    close(p);
    return 0;
}
