/*
 * ghetto_loader.c -- Ghetto Loader for the Cyclone cPCI-820
 *
 * Copyright (C) 2002 Paul Mundt
 * Copyright (C) 2002 TimeSys Corp.
 * 
 * Released under the terms of the GNU GPL v2.
 */
#include <stdio.h>
#include <fcntl.h>
#include <linux/types.h>

static void barrier(void)
{
	int i;

	for (i = 0; i < 0x1000000; i++)
		;
}

int main(int argc, char **argv)
{
	char buf[1];
	int fd, i;
	__u32 base_addr = 0x00000000;
	__u64 total_bytes = 0;

	if (argc != 2) {
		fprintf(stderr, "Usage: %s bin\n", argv[0]);
		return 1;
	}

	fd = open(argv[1], O_RDONLY);

	if (!fd) {
		perror("Can't open file for reading");
		return 1;
	}
	
	/*
	 * This loop of stupidity does a per-byte write-out to stdout,
	 * which in turn needs to be redirected to the correct ttyS
	 * device that Breeze for the cPCI-820 is hooked up to.
	 *
	 * This will loop through fd doing per-byte reads and will
	 * write-out incrementally to the load addr.
	 *
	 * Unfortunately, the cPCI-820 has a UART which is hard-wired
	 * to 9600bps, which means we have to block output with a write
	 * barrier to allow text to finish scrolling..
	 *
	 * After this has completed, execution can happen by jumping to
	 * the base load addr.
	 */
	while ((i = read(fd, buf, sizeof(__u8)))) {
		buf[sizeof(__u8)] = '\0';

		fprintf(stdout, "4");
		fflush(stdout);

		barrier();

		printf("%lx\n", base_addr++);

		barrier();

		printf("%x\n", buf[0]);
		
		barrier();
		fprintf(stderr, "%cWritten %d bytes", 13, ++total_bytes);
	}
	
	fprintf(stderr, "\n");

	close(fd);

	return 0;
}

