/* 
 * This file is subject to the terms and conditions of the GNU General Public
 * License.  See the file "COPYING" in the main directory of this archive
 * for more details.
 *
 * Copyright (C) Hewlett-Packard (Paul Bame) paul_bame@hp.com
 */
#include "bootloader.h"

struct fileio
{
    describe_t describef;
    read_t readf;
};

static struct fileio *fileio = 0;

/* return first available file descriptor or -1 if none
 * could probably die instead of bothering with -1...
 */
int fileio_open(describe_t describef, read_t readf)
{
    int d = -1;
    int i;

    if (fileio == 0)
    {
	unsigned sz = sizeof fileio[0] * MAX_FD;
	fileio = (struct fileio *)malloc(sz);
	memset(fileio, 0, sz);
    }

    for (i = 0; i < MAX_FD; i++)
    {
	if (fileio[i].describef == 0)
	{
	    d = i;
	    fileio[i].describef = describef;
	    fileio[i].readf = readf;
	    break;
	}
    }

    if (Debug)
	printf("assigning fd # %d\n", d);

    return d;
}

void fileio_close(unsigned int fd)
{
    if (fd > MAX_FD)
	return;

    if (Debug)
	printf("closing fd # %d\n", fd);

    memset(&fileio[fd], 0, sizeof(fileio[0]));
}

int seekread(int fd, char *buf, unsigned nbytes, __u64 devaddr)
{
    int r = -1;

    if (0) printf("seekread(%d, 0x%p, %d, 0x%llx)\r\n", fd, buf, nbytes, devaddr);
    if (fileio[fd].readf != 0)
	r = (*fileio[fd].readf)(fd, buf, nbytes, devaddr);

    if (0) printf("seekread(%d) returning %d\r\n", fd, r);
    return r;
}

void describe(int fd, int *bufalign, int *blocksize)
{
    (*fileio[fd].describef)(fd, bufalign, blocksize);
}
