/*

ox16pci952-eeprom.c
A program to dump, program, and examine serial EEPROM images for the
Oxford Semiconductor OX16PCI952 I/O controller

compile:
gcc -W -Wall -std=c99 -g ox16pci952-eeprom.c -lpci -o ox16pci952-eeprom

Written by Ryan Underwood <nemesis@icequake.net>
!!Not supported or endorsed by Oxford Semiconductor!!

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

/* C headers */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>

#define __USE_BSD /* for usleep() */

/* UNIX headers */
#include <getopt.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <unistd.h>

/* Linux headers */
#include <linux/limits.h>
#include <pci/pci.h>
#include <linux/pci_ids.h>

/* Project headers */
#include "ox16pci952.h"

#define NUM_CARDS 4
#define MAX_EEPROM_WORDS 1024
#define DEBUG_DO 0
#define DEBUG_DI 0

int eeprom_words = 0;

volatile uint32_t *get_lcc(struct pci_dev *dev)
{
	uint32_t lcc_addr;
	volatile uint32_t *lcc;
	int fd;

	/* Find MMIO space for LCC */
	if ((fd = open("/dev/mem", O_RDWR)) == -1) {
		perror("open /dev/mem");
		return NULL;
	}
	lcc_addr  = pci_read_long(dev, 0x1c); /* BAR3 */
	if ((lcc = (volatile uint32_t *)mmap(NULL, sizeof(uint32_t),
			PROT_READ|PROT_WRITE, MAP_SHARED, fd, lcc_addr)) == MAP_FAILED) {
		perror("mmap");
		return NULL;
	}
	//printf("lcc: %lx\n", (unsigned long)*lcc);
	return lcc;
	/* leaks fd and mmap */
}

inline void clock(volatile uint32_t *lcc)
{
#if DEBUG_DO
	if (*lcc & LCC_EEPROM_DO)
		printf("1");
	else
		printf("0");
#endif
	*lcc |= LCC_EEPROM_CLK;
	*lcc &= ~LCC_EEPROM_CLK;
}

inline void enable_write(volatile uint32_t *lcc, int addrbits)
{
	int i;

	/* start bit, raise CS, DO */
	*lcc |= LCC_EEPROM_CS | LCC_EEPROM_DO;
	clock(lcc);

	/* cmd(0,0) = en/dis write */
	*lcc &= ~LCC_EEPROM_DO;
	clock(lcc);
	clock(lcc);

	/* enable write: address = 11XXXXXX */
	for (i = 0; i < addrbits; i++) {
		if (i < 2)
			*lcc |= LCC_EEPROM_DO;
		else
			*lcc &= ~LCC_EEPROM_DO;

		clock(lcc);
	}

	/* pulse CS and clear DO to end cycle */
	*lcc &= ~LCC_EEPROM_DO;
	*lcc &= ~LCC_EEPROM_CS;
	clock(lcc);

}

inline void disable_write(volatile uint32_t *lcc, int addrbits)
{
	int i;

	/* start bit, raise CS, DO */
	*lcc |= LCC_EEPROM_CS | LCC_EEPROM_DO;
	clock(lcc);

	/* cmd(0,0) = en/dis write */
	*lcc &= ~LCC_EEPROM_DO;
	clock(lcc);
	clock(lcc);

	*lcc &= ~LCC_EEPROM_DO;
	/* enable write: address = 11XXXXXX */
	for (i = 0; i < addrbits; i++) {
		clock(lcc);
	}

	/* pulse CS and clear DO to end cycle */
	*lcc &= ~LCC_EEPROM_DO;
	*lcc &= ~LCC_EEPROM_CS;
	clock(lcc);

}

inline uint16_t read_word(volatile uint32_t *lcc, int addrbits, uint16_t addr)
{
	int i;
	uint16_t myword;

	/* start bit, raise CS, DO */
	*lcc |= LCC_EEPROM_CS | LCC_EEPROM_DO;
	clock(lcc);

	/* cmd(1,0) = read */
	clock(lcc);
	*lcc &= ~LCC_EEPROM_DO;
	clock(lcc);

	/* write address */
	for (i = addrbits - 1; i >= 0; i--) {
		if (addr & (1 << i))
			*lcc |= LCC_EEPROM_DO;
		else
			*lcc &= ~LCC_EEPROM_DO;

		clock(lcc);
	}
	/* drop DO */
	*lcc &= ~LCC_EEPROM_DO;
//	printf("r");

	myword = 0;
	/* get 16 bits of data */
	for (i = 15; i >= 0; i--) {
		clock(lcc);
		if (*lcc & LCC_EEPROM_DI) {
			myword |= (1 << i);
#if DEBUG_DI
			printf("1");
#endif
		}
#if DEBUG_DI
		else
			printf("0");
#endif
	}
	/* disable CS */
	*lcc &= ~LCC_EEPROM_CS;
	clock(lcc);

//	printf("\n");
//	printf("myword: %x\n", myword);
	return myword;
}

inline int write_word(volatile uint32_t *lcc, int addrbits, uint16_t addr, uint16_t val)
{
	int i;
	int lifeboat;
	int success = 1;

	//printf("%x ", val);

	/* rising edge CS, DO */
	*lcc |= LCC_EEPROM_CS | LCC_EEPROM_DO;
	clock(lcc);

	/* cmd(0,1) = write */
	*lcc &= ~LCC_EEPROM_DO;
	clock(lcc);
	*lcc |= LCC_EEPROM_DO;
	clock(lcc);

	/* write address */
	for (i = addrbits - 1; i >= 0; i--) {
		if (addr & (1 << i))
			*lcc |= LCC_EEPROM_DO;
		else
			*lcc &= ~LCC_EEPROM_DO;

		clock(lcc);
	}
//	printf("r");
	/* write 16 bits of data */
	for (i = 15; i >= 0; i--) {
		if (val & (1 << i))
			*lcc |= LCC_EEPROM_DO;
		else
			*lcc &= ~LCC_EEPROM_DO;
		clock(lcc);
	}
	/* drop CS after writing word */
	*lcc &= ~LCC_EEPROM_CS;
	clock(lcc);

	lifeboat = 0;

	while (1) {
		/* wait for completion */
		usleep(1);
		/* raise CS */
		*lcc |= LCC_EEPROM_CS;
		/* check for done */
		if (*lcc & LCC_EEPROM_DI)
			break; /* done */

		if (lifeboat++ > 10000) {
			/* disable CS */
			*lcc &= ~LCC_EEPROM_CS;
			clock(lcc);
			success = 0;
			break;
		}

		/* lower CS so write continues */
		*lcc &= ~LCC_EEPROM_CS;
		clock(lcc);
	}

	/* drop CS */
	*lcc &= ~LCC_EEPROM_CS;
	clock(lcc);

//	printf("\n");
	return success;
}

enum state {
	ZONE1 = 1,
	ZONE2,
	ZONE3,
	ZONE4,
	FINISH
};

void parse_eeprom(FILE *file)
{
	uint16_t word;
	int state;
	int i;
	int zone1 = 0, zone2 = 0, zone3 = 0, zone4 = 0;
	int entered;
	int z1pair = 0, z1write = 0;
	int z3count = 0;
	int z4uart = 0, z4lpt = 0;
	int wordcount = 0;
	int padcount = 0;

	fseek(file, 0, SEEK_SET);

	printf("Header info:\n");
	if (fread(&word, sizeof(uint16_t), 1, file) < 1) {
		perror("fread");
		return;
	}
	word = ntohs(word);
	wordcount++;
	printf("Header magic: 0x%x, ", (word & 0xFFF0) >> 4);
	if ((word & 0xFFF0) >> 4 == 0x950)
		printf("valid\n");
	else
		printf("invalid\n");

	if (word & (1 << 0)) {
		zone4 = 1;
		state = ZONE4;
	}
	if (word & (1 << 1)) {
		zone3 = 1;
		state = ZONE3;
	}
	if (word & (1 << 2)) {
		zone2 = 1;
		state = ZONE2;
	}
	if (word & (1 << 3)) {
		zone1 = 1;
		state = ZONE1;
	}

	if (zone1)
		printf("Zone1 (Function Access) exists\n");
	else
		printf("Zone1 does not exist\n");
	if (zone2)
		printf("Zone2 (Local Configuration Registers) exists\n");
	else
		printf("Zone2 does not exist\n");
	if (zone3)
		printf("Zone3 (Identification Registers) exists\n");
	else
		printf("Zone3 does not exist\n");
	if (zone4)
		printf("Zone4 (PCI Configuration Registers) exists\n");
	else
		printf("Zone4 does not exist\n");

	entered = 1;
	while (state == ZONE1) {

		if (entered) {
			printf("Zone1: Function Access");
			entered = 0;
		}

		/* get next word */
		if (fread(&word, sizeof(uint16_t), 1, file) < 1) {
			perror("fread");
			return;
		}

		word = ntohs(word);
		wordcount++;

		if (z1pair) {
			uint8_t data;
			if (!(word & 0x8000))
				printf("warning: Zone 1 data_write word did not have a leading 1\n");

			if (word & 0x7F00)
				printf("warning: Used reserved bits in Zone 1 data_write word\n");

			if (!z1write && (word & 0xF))
				printf("warning: Set data_write bits when read is taking place\n");

			data = word & 0xFF;
			printf("%.2x", data);
			z1pair = 0;
			continue;
		}
		if (word & 0x8000) {
			int bar, rw, func;
			uint8_t addr;
			bar = (word & 0x7000) >> 12;
			rw = 0 || (word & 0x0800);
			func = (word & 0x0700) >> 8;
			addr = word & 0xFF;
			printf("\n");
			switch (func) {
				case 0:
				case 1:
					break;
				default:
					printf("warning: Tried to use a reserved function number in Zone 1\n");
					break;
			}
			switch (bar) {
				case 0:
				case 1:
					break;
				default:
					printf("warning: Tried to use a reserved BAR number in Zone 1\n");
					break;
			}

			printf("Zone 1 ");
			switch (func) {
				case 0:
					printf("UARTs function, ");
					break;
				case 1:
					printf("Parallel Port function, ");
					break;
				default:
					printf("warning: Tried to use a reserved function number in Zone 1\n");
					break;
			}
			switch (bar) {
				case 0:
					printf("BAR0 ");
					switch(func) {
						case 0:
							printf("(UART0) ");
						case 1:
							printf("(Parallel Port Base Registers) ");
						default:
							break;
					}
					break;
				case 1:
					printf("BAR1 ");
					switch(func) {
						case 0:
							printf("(UART1) ");
						case 1:
							printf("(Parallel Port Extended Registers) ");
						default:
							break;
					}
					break;
				default:
					printf("warning: Tried to use a reserved BAR number in Zone 1\n");
					break;
			}

			z1write = 0;
			switch(rw) {
				case 1:
					printf("[0x%.2x] = ", addr);
					z1write = 1;
					break;
				default:
					printf("Read [0x%.2x] (discard data)", addr);
					break;
			}

			z1pair = 1;
			continue;
		}

		/* state transition */
		if (zone2)
			state = ZONE2;
		else if (zone3)
			state = ZONE3;
		else if (zone4)
			state = ZONE4;
		else
			state = FINISH;
		printf("\nZone 1 End\n");
		entered = 1;
	}

	while (state == ZONE2) {

		uint8_t offset, val;

		/* get next word */
		if (fread(&word, sizeof(uint16_t), 1, file) < 1) {
			perror("fread");
			return;
		}
		word = ntohs(word);
		wordcount++;

		if (entered) {
			printf("Zone2: Local Configuration Register Zone\n");
			entered = 0;
		}

		offset = (word & 0x7F00) >> 8;
		val = word & 0xFF;

		printf("LCR(0x%.2x)[%d:%d] = %.2x\n", offset - (offset % 4), (8*(offset%4))+7, 8*(offset%4), val);

		if (word & 0x8000)
			continue;

		/* state transition */
		if (zone3)
			state = ZONE3;
		else if (zone4)
			state = ZONE4;
		else
			state = FINISH;
		printf("Zone 2 End\n");
		entered = 1;
	}
	while (state == ZONE3) {

		int reg;
		uint8_t val;
		int id1 = 0, id2 = 0, id3 = 0, id4 = 0;

		/* get next word */
		if (fread(&word, sizeof(uint16_t), 1, file) < 1) {
			perror("fread");
			return;
		}
		word = ntohs(word);
		wordcount++;

		if (entered) {
			printf("Zone3: Identification Registers\n");
			entered = 0;
		}

		reg = (word & 0x7F00) >> 8;
		val = word & 0xFF;

		switch(reg) {
			case 0x00:
				if (id1) {
					printf("warning: Vendor ID bits [7:0] programmed more than once\n");
				}
				printf("Vendor ID bits [7:0]: %.2x\n", val);
				id1 = 1;
				break;
			case 0x01:
				if (id2) {
					printf("warning: Vendor ID bits [15:8] programmed more than once\n");
				}
				printf("Vendor ID bits [15:8]: %.2x\n", val);
				id2 = 1;
				break;
			case 0x02:
				if (id3) {
					printf("warning: Subsystem Vendor ID bits [7:0] programmed more than once\n");
				}
				printf("Subsystem Vendor ID bits [7:0]: %.2x\n", val);
				id3 = 1;
				break;
			case 0x03:
				if (id4) {
					printf("warning: Subsystem Vendor ID bits [15:8] programmed more than once\n");
				}
				printf("Subsystem Vendor ID bits [15:8]: %.2x\n", val);
				id4 = 1;
				break;
			default:
				printf("warning: Tried to configure a reserved identification register 0x%.2x\n", reg);
				break;
		}

		z3count++;
		if (word & 0x8000) {
			if (z3count == 4) {
				printf("warning: Zone 3 has more than 4 words, spec violated\n");
			}
			continue;
		}

		if ((id1 && !id2) || (!id1 && id2)) {
			printf("warning: Only part of the Vendor ID was programmed\n");
		}
		if ((id3 && !id4) || (!id3 && id4)) {
			printf("warning: Only part of the Subsystem Vendor ID was programmed\n");
		}

		/* state transition */
		if (zone4)
			state = ZONE4;
		else
			state = FINISH;
		printf("Zone 3 End\n");
		entered = 1;
	}
	while (state == ZONE4) {

		/* get next word */
		if (fread(&word, sizeof(uint16_t), 1, file) < 1) {
			perror("fread");
			return;
		}
		word = ntohs(word);
		wordcount++;

		if (entered) {
			printf("Zone4: PCI Configuration Registers\n");
			entered = 0;
		}

		if (z4uart) {
			uint8_t offset, val;
			offset = (word & 0x7F00) >> 8;
			val = word & 0xFF;
			
			printf("PCI Configuration[0x%.2x] = %.2x\n", offset, val);

			if ((word & 0x8000) == 0)
				z4uart = 0; /* leave UART state */
			continue;
		}
		else if (z4lpt) {
			uint8_t offset, val;
			offset = (word & 0x7F00) >> 8;
			val = word & 0xFF;

			switch(offset) {
				case 0x00:
				case 0x01:
				case 0x02:
				case 0x03:
				case 0x06:
				case 0x09:
				case 0x0A:
				case 0x0B:
				case 0x0E:
				case 0x2E:
				case 0x2F:
				case 0x3D:
				case 0x42:
				case 0x43:
					printf("PCI Configuration[0x%.2x] = %.2x\n", offset, val);
					break;
				default:
					printf("warning: operation PCI Configuration[0x%.2x] = %.2x cannot be performed by EEPROM program\n", offset, val);
					break;
			}

			if ((word & 0x8000) == 0)
				z4lpt = 0; /* leave LPT state */
			continue;
		}
		else if (word & 0x8000) {
			uint8_t function = 0 || (word & 7);
			if (word & 0x7FF8)
				printf("warning: Writing to reserved bits in Zone 4 function header\n");

			switch(function) {
				case 0:
					printf("Zone 4 Header, PCI Configuration for UART Function\n");
					z4uart = 1;
					break;
				case 1:
					printf("Zone 4 Header, PCI Configuration for Parallel Port Function\n");
					z4lpt = 1;
					break;
				default:
					printf("warning: Using a reserved function value 0x%.2x in Zone 4 function header\n", function);
					break;
			}

			continue;
		}

		printf("Zone 4 End\n");
		/* state transition */
		state = FINISH;
	}

	/* Print any junk at the end, just so the user is aware of it */
	while (fread(&word, sizeof(uint16_t), 1, file) == 1) {
		if (!padcount) {
			printf("Padding words in EEPROM image after end of program:\n");
			for (i = 0; i < wordcount % 8; i++)
				printf("     ");
		}
		padcount++;
		word = ntohs(word);
		printf("%.4x ", word);
		if (((wordcount+padcount) % 8) == 0)
			printf("\n");
	}
	if (padcount)
		printf("\n");

	if (!feof(file))
		printf("warning: Error encountered reading to end of file\n");

}

void dump_eeprom(struct pci_dev *dev, FILE *file, int *addrbits)
{
	int good = 0;
	int bits1024 = 10;
	int search = 0;
	volatile uint32_t *lcc = get_lcc(dev);

	if (*addrbits == 0) {
		*addrbits = 6; /* Start with 64-word eeprom */
		search = 1;
	}

//	printf("lcc: %lx mio: %lx\n", *lcc, *(lcc+1));
	if (!((*lcc) & LCC_EEPROM_VALID)) {
		printf("Note: current EEPROM image is considered invalid by the board\n");
	}

	/* Get 16-bit header, and determine how many address bits to use */
	while (!good) {
		uint16_t header;
		header = read_word(lcc, *addrbits, 0);
		if ((header & 0xFFF0) >> 4 == 0x950) {
			good = 1;
		}
		else {
			if (!search || *addrbits >= bits1024)
			{
				printf("Couldn't find a valid EEPROM (could be corrupt, or wrong address bits)\n");
				return;
			}
			(*addrbits)++;
		}
	}

	printf("Valid header found (address bits = %d)\n", *addrbits);

	if (eeprom_words == 0) {
		printf("Error: must supply number of EEPROM words (-w)\n");
		return;
	}
	printf("Dumping eeprom to file...\n");

	for (int i = 0; i < eeprom_words; i++) {
		uint16_t word;
		word = read_word(lcc, *addrbits, i);
		/* Image file is MSB-first */
		word = htons(word);
		if (fwrite(&word, sizeof(uint16_t), 1, file) < 1) {
			perror("fwrite");
			return;
		}
	}
}

int check_eeprom_image(FILE *file, int *length, uint16_t *csum)
{
	int supposed_length = *length;
	uint16_t word;
	int bad_hdr = 0;
	int first = 1;

	if (csum != NULL)
		*csum = 0;

	*length = 0;
	fseek(file, 0, SEEK_SET);
	while (fread(&word, sizeof(uint16_t), 1, file) == 1) {
		/* image file stored in MSB-first order */
		word = ntohs(word);

		if (first) { /* header word */
			if ((word & 0xFFF0) >> 4 != 0x950) {
				bad_hdr = 1;
			}
		}

		if (csum != NULL)
			*csum += word;

		(*length)++;
		first = 0;
	}

	if (bad_hdr || *length != supposed_length)
		return 0;

	return 1;
}

void load_eeprom(struct pci_dev *dev, FILE *file, int addrbits)
{

	uint16_t source_csum, dump_csum;
	volatile uint32_t *lcc = get_lcc(dev);
	FILE *check;
	int length;

	if (addrbits == 0) {
		printf("Error: must supply number of address bits for installed EEPROM (-a)\n");
		return;
	}

	if (eeprom_words == 0) {
		printf("Error: must supply number of EEPROM words (-w)\n");
		return;
	}

	length = eeprom_words;
	/* validate file length and compute checksum */
	if (!check_eeprom_image(file, &length, &source_csum)) {
		printf("Input EEPROM image file is invalid.\n");
		if (length != eeprom_words) {
			printf("Source file words %d doesn't match given EEPROM size %d\n", length, eeprom_words);
			return;
		}
		return;
	}

	printf("source file csum: %x, len %d words\n", source_csum, length);

	/* upload */
	
	enable_write(lcc, addrbits);

	printf("Uploading to EEPROM...\n");
	fseek(file, 0, SEEK_SET);

	for (int i = 0; i < eeprom_words; i++) {
		uint16_t word;
		if (fread(&word, sizeof(uint16_t), 1, file) < 1) {
			printf("Error reading from source file.  Aborting upload.\n");
			return;
		}
		/* Convert to big endian before writing */
		word = htons(word);
		if (!write_word(lcc, addrbits, i, word)) {
			printf("Error in EEPROM protocol.  Aborting upload.\n");
			return;
		}
	}

	disable_write(lcc, addrbits);

	check = tmpfile();
	/* dump eeprom, compare to source file checksum */
	dump_eeprom(dev, check, &addrbits);
	length = eeprom_words;
	if (!check_eeprom_image(check, &length, &dump_csum)) {
		printf("Dump file is invalid, upload was corrupted somehow?\n");
		return;
	}
	fclose(check);

	if (dump_csum != source_csum) {
		printf("Dump checksum %x didn't match source checksum %x, upload was corrupted?\n", dump_csum, source_csum);
		return;
	}
	printf("Upload verified.\n");
	printf("Resetting board with new EEPROM configuration... ");
	*lcc |= LCC_EEPROM_RELOAD;
	if ((*lcc) & LCC_EEPROM_VALID)
		printf("complete.\n");
	else
		printf("failed (EEPROM corrupt?)\n");

}

void print_help(void)
{
	printf(
"-h\t\t\tprint help\n"
"-w <words>\t\tnumber of words of installed EEPROM (required, 64-1024)\n"
"-i <index>\t\tcard index (for systems with multiple cards)\n"
"-d <file>\t\tdump EEPROM to file\n"
"-a <addrbits>\t\tspecify number of address bits for uploading\n"
"-u <file>\t\tupload EEPROM from file using the specified number of address bits\n"
"-p <file>\t\tparse dump file to plain text description\n"
	);
}

enum cmds {
	CMD_UPLOAD = 1,
	CMD_DOWNLOAD,
	CMD_PARSE
};

int main(int argc, char **argv)
{
	struct pci_access *pacc;
	struct pci_dev *pdev;
	int found = 0;
	struct pci_dev *devs[NUM_CARDS];
	int dev_index = 0;
	int fd;
	char opt;
	FILE *file;
	int opterror = 0;
	unsigned char cmd = 0;
	char fname[PATH_MAX];
	int addrbits = 0;

	pacc = pci_alloc();
	pci_init(pacc);
	pci_scan_bus(pacc);

	pdev = pacc->devices;
	while (pdev) {
		if (pdev->vendor_id == PCI_VENDOR_ID_OXSEMI && pdev->device_id == 0x9521)
		{
			if (found < NUM_CARDS) {
				devs[found] = pdev;
				found++;
			}
			else
				printf("Ignoring cards greater than %d\n", NUM_CARDS);
		}
	
		pdev = pdev->next;
	}

	printf("OX16PCI952: ");
	if (!found) {
		printf("not found\n");
		pci_cleanup(pacc);
		exit(EXIT_FAILURE);
	}
	printf("%d found\n", found);

	if (argc < 2) {
		print_help();
		pci_cleanup(pacc);
		exit(EXIT_FAILURE);
	}

	/* process options */
	while (!opterror && (opt = getopt(argc, argv, "hw:i:a:p:d:u:")) != -1) {
		switch(opt) {
		case 'w':
			eeprom_words = strtoul(optarg, NULL, 10);
			break;
		case 'i':
			dev_index = strtoul(optarg, NULL, 10);
			if (dev_index >= NUM_CARDS) {
				printf("index %d greater than %d\n", dev_index, NUM_CARDS);
				opterror = 1;
			}
			break;
		case 'a':
			addrbits = strtoul(optarg, NULL, 10);
			if (addrbits < 6 || addrbits > 10) {
				printf("invalid number of address bits\n");
				opterror = 1;
			}
			break;
		case 'p':
			if (cmd) {
				printf("multiple commands given\n");
				opterror = 1;
				break;
			}
			cmd = CMD_PARSE;
			strncpy(fname, optarg, PATH_MAX-1);
			fname[PATH_MAX-1] = '\0';
			break;
		case 'd':
			if (cmd) {
				printf("multiple commands given\n");
				opterror = 1;
				break;
			}
			cmd = CMD_DOWNLOAD;
			strncpy(fname, optarg, PATH_MAX-1);
			fname[PATH_MAX-1] = '\0';
			break;
		case 'u':
			if (cmd) {
				printf("multiple commands given\n");
				opterror = 1;
				break;
			}
			cmd = CMD_UPLOAD;
			strncpy(fname, optarg, PATH_MAX-1);
			fname[PATH_MAX-1] = '\0';
			break;
		case 'h':
		default:
			print_help();
			opterror = 1;
			break;
		}
	}

	if (!opterror && cmd) {
		switch(cmd) {
			case CMD_PARSE:
				if ((file = fopen(fname, "r")) == NULL) {
					perror("fopen");
					opterror = 1;
					break;
				}
				parse_eeprom(file);
				break;
			case CMD_UPLOAD:
				if ((fd = open("/dev/mem", O_RDWR)) == -1) {
					printf("Couldn't open /dev/mem; you should probably be root\n");
					pci_cleanup(pacc);
					exit(EXIT_SUCCESS);
				}
				close(fd);

				if ((file = fopen(fname, "r")) == NULL) {
					perror("fopen");
					opterror = 1;
					break;
				}
				load_eeprom(devs[dev_index], file, addrbits);
				break;
			case CMD_DOWNLOAD:
				if ((fd = open("/dev/mem", O_RDWR)) == -1) {
					printf("Couldn't open /dev/mem; you should probably be root\n");
					pci_cleanup(pacc);
					exit(EXIT_SUCCESS);
				}
				close(fd);

				if ((file = fopen(fname, "w")) == NULL) {
					perror("fopen");
					opterror = 1;
					break;
				}
				dump_eeprom(devs[dev_index], file, &addrbits);
				printf("number of EEPROM address bits: %d (remember this for writing!)\n", addrbits);
				break;
			default:
				abort();
				break;
		}
		fclose(file);
	}

	pci_cleanup(pacc);

	if (opterror)
		exit(EXIT_FAILURE);

	exit(EXIT_SUCCESS);

}

