/*======================================================================

    PCMCIA Card Information Structure parser

    Written by David Hinds, dhinds@allegro.stanford.edu
    
======================================================================*/

#include <pcmcia/config.h>
#define __NO_VERSION__
#include <pcmcia/k_compat.h>

#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/major.h>
#include <linux/errno.h>
#include <linux/timer.h>
#include <linux/malloc.h>
#include <linux/mm.h>
#include <linux/sched.h>
#include <asm/io.h>

#include <pcmcia/cs_types.h>
#include <pcmcia/ss.h>
#include <pcmcia/cs.h>
#include <pcmcia/bulkmem.h>
#include <pcmcia/cistpl.h>
#include "cs_internal.h"
#include "rsrc_mgr.h"

#define MIN(a, b) (((a) < (b)) ? (a) : (b))

static const u_char mantissa[] = {
    10, 12, 13, 15, 20, 25, 30, 35,
    40, 45, 50, 55, 60, 70, 80, 90
};

static const u_long exponent[] = {
    1, 10, 100, 1000, 10000, 100000, 1000000, 10000000
};

/* Convert an extended speed byte to a time in nanoseconds */
#define SPEED_CVT(v) \
    (mantissa[(((v)>>3)&15)-1] * exponent[(v)&7] / 10)
/* Convert a power byte to a current in 0.1 microamps */
#define POWER_CVT(v) \
    (mantissa[((v)>>3)&15] * exponent[(v)&7] / 10)
#define POWER_SCALE(v) (exponent[(v)&7])

/* Upper limit on reasonable # of tuples */
#define MAX_TUPLES 200

/*======================================================================

    Low-level functions to read and write CIS memory.  I think the
    write routine is only useful for writing one-byte registers.
    
======================================================================*/

void read_cis_mem(socket_info_t *s, int attr,
		  long addr, long len, u_char *ptr)
{
    pcmcia_mem_map *mem = &s->cis_mem;
    u_char *sys = (u_char *)(mem->sys_start + (addr & 0x0fff));
    int inc = 1;
    
    DEBUG(3, "cs: read_cis_mem(%d, %#lx, %ld)\n", attr, addr, len);
    mem->card_start = addr & ~0x0fff;
    mem->flags &= ~MAP_ATTRIB;
    if (attr) { mem->flags |= MAP_ATTRIB; inc++; }
    
    for (; len > 0; mem->card_start += 0x1000, sys -= 0x1000) {
	s->ss_entry(s->sock, SS_SetMemMap, mem);
	DEBUG(3, "cs:  %#2.2x %#2.2x %#2.2x %#2.2x %#2.2x ...\n",
	      sys[0], sys[inc], sys[2*inc], sys[3*inc], sys[4*inc]);
	for ( ; len > 0; len--, ptr++, sys += inc) {
	    if (sys > (u_char *)mem->sys_stop) break;
	    *ptr = readb(sys);
	}
    }
} /* read_cis_mem */

void write_cis_mem(socket_info_t *s, int attr,
		   long addr, long len, u_char *ptr)
{
    pcmcia_mem_map *mem = &s->cis_mem;
    u_char *sys = (u_char *)(mem->sys_start + (addr & 0x0fff));
    int inc = 1;
    
    mem->card_start = addr & ~0x0fff;
    mem->flags &= ~MAP_ATTRIB;
    if (attr) { mem->flags |= MAP_ATTRIB; inc++; }
    
    for (; len > 0; mem->card_start += 0x1000, sys -= 0x1000) {
	s->ss_entry(s->sock, SS_SetMemMap, mem);
	for ( ; len > 0; len--, ptr++, sys += inc) {
	    if (sys > (u_char *)mem->sys_stop) break;
	    writeb(*ptr, sys);
	}
    }
} /* write_cis_mem */

int setup_cis_mem(socket_info_t *s)
{
    /* Validation function for cards with a valid CIS */
    int cis_readable(u_long base)
    {
	cisinfo_t info;
	int ret;
	s->cis_mem.sys_start = base;
	s->cis_mem.sys_stop = base+0x0fff;
	ret = validate_cis(s->clients, &info);
	s->cis_used = 0; /* invalidate CIS cache */
	return ((ret == 0) && (info.Chains > 0));
    }

    /* Validation function for simple memory cards */
    int checksum(u_long base)
    {
	int i, a;
	s->cis_mem.sys_start = base;
	s->cis_mem.sys_stop = base+0xfff;
	s->cis_mem.card_start = 0;
	s->cis_mem.flags = MAP_ACTIVE;
	s->ss_entry(s->sock, SS_SetMemMap, &s->cis_mem);
	/* Don't bother checking every word... */
	for (i = a = 0; i < 0x1000; i += 53)
	    a += (int)readl(base+i);
	return a;
    }

    int checksum_match(u_long base)
    {
	return (checksum(base) == checksum(base+0x1000));
    }
    
    static int first = 1;
    if (s->cis_mem.sys_start == 0) {
	if (first == 1) {
	    first = 0;
	    validate_mem(cis_readable, checksum_match);
	    s->cis_mem.sys_start = 0;
	}
	if (find_mem_region(&s->cis_mem.sys_start,
			    0x1000, "card services") != 0)
	    return CS_OUT_OF_RESOURCE;
	s->cis_mem.sys_stop = s->cis_mem.sys_start + 0x0fff;
    }
    return 0;
} /* setup_cis_mem */

/*======================================================================

    This is a wrapper around read_cis_mem, with the same interface,
    but which caches information, for cards whose CIS may not be
    readable all the time.
    
======================================================================*/

static void read_cis_cache(socket_info_t *s, int attr,
			   long addr, long len, u_char *ptr)
{
    int i;
    char *caddr;

    caddr = s->cis_cache;
    for (i = 0; i < s->cis_used; i++) {
	if ((s->cis_table[i].addr == addr) &&
	    (s->cis_table[i].len == len) &&
	    (s->cis_table[i].attr == attr)) break;
	caddr += s->cis_table[i].len;
    }
    if (i < s->cis_used) {
	memcpy(ptr, caddr, len);
	return;
    }
    read_cis_mem(s, attr, addr, len, ptr);
    /* Copy data into the cache, if there is room */
    if ((i < MAX_CIS_TABLE) &&
	(caddr+len < s->cis_cache+MAX_CIS_DATA)) {
	s->cis_table[i].addr = addr;
	s->cis_table[i].len = len;
	s->cis_table[i].attr = attr;
	s->cis_used++;
	memcpy(caddr, ptr, len);
    }	    
}

/*======================================================================

    This verifies if the CIS of a card matches what is in the CIS
    cache.
    
======================================================================*/

int verify_cis_cache(socket_info_t *s)
{
    char buf[256], *caddr;
    int i;
    
    caddr = s->cis_cache;
    for (i = 0; i < s->cis_used; i++) {
	read_cis_mem(s, s->cis_table[i].attr, s->cis_table[i].addr,
		     s->cis_table[i].len, buf);
	if (memcmp(buf, caddr, s->cis_table[i].len) != 0)
	    break;
	caddr += s->cis_table[i].len;
    }
    return (i < s->cis_used);
}

/*======================================================================

    Read tuple codes from attribute memory.
    
======================================================================*/

#define LINK_MFC_N	0x00ff
#define LINK_C		0x0100
#define LINK_A		0x0200
#define LINK_MFC	0x0400
#define IS_ATTR 	0x1000
#define MFC_IS_ATTR	0x2000

int get_next_tuple(client_handle_t handle, tuple_t *tuple);

int get_first_tuple(client_handle_t handle, tuple_t *tuple)
{
    if (CHECK_HANDLE(handle))
	return CS_BAD_HANDLE;
    tuple->CISOffset = -1;
    if ((SOCKET(handle)->functions > 1) &&
	!(tuple->Attributes & TUPLE_RETURN_COMMON)) {
	cisdata_t req = tuple->DesiredTuple;
	tuple->DesiredTuple = CISTPL_LONGLINK_MFC;
	if (get_next_tuple(handle, tuple) == CS_SUCCESS) {
	    tuple->DesiredTuple = CISTPL_LINKTARGET;
	    if (get_next_tuple(handle, tuple) != CS_SUCCESS)
		return CS_NO_MORE_ITEMS;
	} else
	    tuple->CISOffset = -1;
	tuple->DesiredTuple = req;
    }
    return get_next_tuple(handle, tuple);
} /* get_first_tuple */

static long follow_link(socket_info_t *s, tuple_t *tuple)
{
    u_char link[5];
    long ofs;
    
    switch (tuple->Flags & (LINK_A|LINK_C|LINK_MFC)) {
    case LINK_A:
	ofs = tuple->LinkOffset;
	tuple->Flags = IS_ATTR;
	break;
    case LINK_C:
	ofs = tuple->LinkOffset;
	tuple->Flags = 0;
	break;
    case LINK_MFC:
	/* Get indirect link from the MFC tuple */
	read_cis_cache(s, tuple->Flags & MFC_IS_ATTR,
		       tuple->LinkOffset, 5, link);
	ofs = *(long *)(link+1);
	if (link[0] == CISTPL_MFC_ATTR)
	    tuple->Flags |= IS_ATTR;
	else
	    tuple->Flags &= ~IS_ATTR;
	/* Move to the next indirect link */
	tuple->Flags--;
	tuple->LinkOffset += (tuple->Flags & MFC_IS_ATTR) ? 10 : 5;
	if ((tuple->Flags & LINK_MFC_N) == 0)
	    tuple->Flags &= ~LINK_MFC;
	break;
    default:
	return -1;
    }
    if (tuple->Flags & IS_ATTR) {
	ofs = ofs << 1;
	/* This is ugly, but a common CIS error is to code the long
	   link offset incorrectly, so we check the right spot... */
	read_cis_cache(s, tuple->Flags & IS_ATTR, ofs, 5, link);
	if ((link[0] == CISTPL_LINKTARGET) && (link[1] >= 3) &&
	    (strncmp(link+2, "CIS", 3) == 0))
	    return ofs;
	/* Then, we try the wrong spot... */
	ofs = ofs >> 1;
    }
    read_cis_cache(s, tuple->Flags & IS_ATTR, ofs, 5, link);
    if ((link[0] != CISTPL_LINKTARGET) || (link[1] < 3) ||
	(strncmp(link+2, "CIS", 3) != 0))
	return -1;
    return ofs;
} /* follow_link */

int get_next_tuple(client_handle_t handle, tuple_t *tuple)
{
    socket_info_t *s;
    u_char link[2], tmp;
    long ofs;
    int i, attr;
    
    if (CHECK_HANDLE(handle))
	return CS_BAD_HANDLE;

    s = SOCKET(handle);
    if (setup_cis_mem(s) != 0)
	return CS_OUT_OF_RESOURCE;

    if (tuple->CISOffset == -1) {
	ofs = 0;
	/* Assume presence of a LONGLINK_C to address 0 */
	tuple->LinkOffset = 0;
	tuple->Flags = IS_ATTR | LINK_C;
    }
    else {
	if (tuple->TupleLink == 0xff) {
	    if ((ofs = follow_link(s, tuple)) < 0)
		return CS_NO_MORE_ITEMS;
	}
	else
	    ofs = tuple->CISOffset +
		((tuple->Flags & IS_ATTR) ? 2 : 1) * (tuple->TupleLink+2);
    }
    attr = tuple->Flags & IS_ATTR;
    
    for (i = 0; i < MAX_TUPLES; i++) {
	read_cis_cache(s, attr, ofs, 2, link);

	if (link[0] == CISTPL_NULL) {
	    ofs += attr ? 2 : 1;
	    continue;
	}
	
	/* End of chain?  Follow long link if possible */
	if (link[0] == CISTPL_END) {
	    if ((ofs = follow_link(s, tuple)) < 0)
		return CS_NO_MORE_ITEMS;
	    attr = tuple->Flags & IS_ATTR;
	    read_cis_cache(s, attr, ofs, 2, link);
	}

	/* Is this a link tuple?  Make a note of it */
	if ((link[0] == CISTPL_LONGLINK_A) ||
	    (link[0] == CISTPL_LONGLINK_C) ||
	    (link[0] == CISTPL_LONGLINK_MFC) ||
	    (link[0] == CISTPL_LINKTARGET) ||
	    (link[0] == CISTPL_NO_LINK)) {
	    switch (link[0]) {
	    case CISTPL_LONGLINK_A:
		tuple->Flags = attr | LINK_A;
		read_cis_cache(s, attr, ofs + (attr ? 4 : 2), 4,
			       (u_char *)&tuple->LinkOffset);
		break;
	    case CISTPL_LONGLINK_C:
		tuple->Flags = attr | LINK_C;
		read_cis_cache(s, attr, ofs + (attr ? 4 : 2), 4,
			       (u_char *)&tuple->LinkOffset);
		break;
	    case CISTPL_LONGLINK_MFC:
		if (handle->Function == BIND_FN_ALL) {
		    /* Follow all the MFC links */
		    read_cis_cache(s, attr, ofs + (attr ? 4 : 2), 1,
				 (u_char *)&tmp);
		    tuple->Flags = attr | LINK_MFC | tmp;
		    tuple->LinkOffset = ofs + (attr ? 6 : 3);
		}
		else {
		    /* Follow exactly one of the links */
		    tuple->Flags = attr | LINK_MFC | 1;
		    tuple->LinkOffset = ofs + (attr ? 2 : 1) *
			(3 + handle->Function * 5);
		}
		if (attr)
		    tuple->Flags |= MFC_IS_ATTR;
		break;
	    case CISTPL_NO_LINK:
		tuple->Flags = attr;
		break;
	    }
	    if ((tuple->Attributes & TUPLE_RETURN_LINK) &&
		(tuple->DesiredTuple == RETURN_FIRST_TUPLE))
		break;
	}
	else
	    if (tuple->DesiredTuple == RETURN_FIRST_TUPLE)
		break;
	
	if (link[0] == tuple->DesiredTuple)
	    break;
	ofs += (attr ? 2 : 1) * (link[1]+2);
    }
    if (i == MAX_TUPLES) {
#ifdef PCMCIA_DEBUG
	printk(KERN_DEBUG "cs: overrun in get_next_tuple for "
	       "socket %d\n", handle->Socket);
#endif
	return CS_NO_MORE_ITEMS;
    }
    
    tuple->TupleCode = link[0];
    tuple->TupleLink = link[1];
    tuple->CISOffset = ofs;
    return CS_SUCCESS;
} /* get_next_tuple */

/*====================================================================*/

int get_tuple_data(client_handle_t handle, tuple_t *tuple)
{
    socket_info_t *s;
    u_long len;
    
    if (CHECK_HANDLE(handle))
	return CS_BAD_HANDLE;

    s = SOCKET(handle);
    if (setup_cis_mem(s) != 0)
	return CS_OUT_OF_RESOURCE;

    if (tuple->TupleLink < tuple->TupleOffset)
	return CS_NO_MORE_ITEMS;
    len = tuple->TupleLink - tuple->TupleOffset;
    tuple->TupleDataLen = tuple->TupleLink;
    if (len == 0)
	return CS_SUCCESS;
    if (tuple->Flags & IS_ATTR)
	read_cis_cache(s, 1, tuple->CISOffset+((tuple->TupleOffset+2)<<1),
		       MIN(len, tuple->TupleDataMax), tuple->TupleData);
    else
	read_cis_cache(s, 0, tuple->CISOffset+(tuple->TupleOffset+2),
		       MIN(len, tuple->TupleDataMax), tuple->TupleData);
    return CS_SUCCESS;
} /* get_tuple_data */

/*======================================================================

    Parsing routines for individual tuples
    
======================================================================*/

static int parse_device(tuple_t *tuple, cistpl_device_t *device)
{
    int i;
    u_char scale;
    u_char *p, *q;

    p = (u_char *)tuple->TupleData;
    q = p + tuple->TupleDataLen;

    device->ndev = 0;
    for (i = 0; i < CISTPL_MAX_DEVICES; i++) {
	
	if (*p == 0xff) break;
	device->dev[i].type = (*p >> 4);
	device->dev[i].wp = (*p & 0x08) ? 1 : 0;
	switch (*p & 0x07) {
	case 0: device->dev[i].speed = 0;   break;
	case 1: device->dev[i].speed = 250; break;
	case 2: device->dev[i].speed = 200; break;
	case 3: device->dev[i].speed = 150; break;
	case 4: device->dev[i].speed = 100; break;
	case 7:
	    if (++p == q) return CS_BAD_TUPLE;
	    if (p == q)
		return CS_BAD_TUPLE;
	    device->dev[i].speed = SPEED_CVT(*p);
	    while (*p & 0x80)
		if (++p == q) return CS_BAD_TUPLE;
	    break;
	default:
	    return CS_BAD_TUPLE;
	}

	if (++p == q) return CS_BAD_TUPLE;
	if (*p == 0xff) break;
	scale = *p & 7;
	if (scale == 7) return CS_BAD_TUPLE;
	device->dev[i].size = ((*p >> 3) + 1) * (512 << (scale*2));
	device->ndev++;
	if (++p == q) break;
    }
    
    return CS_SUCCESS;
} /* parse_device */

/*====================================================================*/

static int parse_checksum(tuple_t *tuple, cistpl_checksum_t *csum)
{
    char *p;
    if (tuple->TupleDataLen < 5)
	return CS_BAD_TUPLE;
    p = (char *)tuple->TupleData;
    csum->addr = *(u_short *)p;
    csum->len = *(u_short *)(p + 2);
    csum->sum = *(p+4);
    return CS_SUCCESS;
} /* parse_checksum */

/*====================================================================*/

static int parse_longlink(tuple_t *tuple, cistpl_longlink_t *link)
{
    if (tuple->TupleDataLen < 4)
	return CS_BAD_TUPLE;
    link->addr = *(u_long *)tuple->TupleData;
    return CS_SUCCESS;
} /* parse_longlink */

/*====================================================================*/

static int parse_longlink_mfc(tuple_t *tuple,
			      cistpl_longlink_mfc_t *link)
{
    u_char *p;
    int i;
    
    p = (char *)tuple->TupleData;
    
    link->nfn = *p; p++;
    if (tuple->TupleDataLen <= link->nfn*5)
	return CS_BAD_TUPLE;
    for (i = 0; i < link->nfn; i++) {
	link->fn[i].space = *p; p++;
	link->fn[i].addr = *(u_long *)p; p += 4;
    }
    return CS_SUCCESS;
}

/*====================================================================*/

static int parse_strings(u_char *p, u_char *q, int max,
			 char *s, int *ofs, int *found)
{
    int i, j, ns;

    if (p == q) return CS_BAD_TUPLE;
    ns = 0; j = 0;
    for (i = 0; i < max; i++) {
	if (*p == 0xff) break;
	ofs[i] = j;
	ns++;
	for (;;) {
	    s[j++] = (*p == 0xff) ? '\0' : *p;
	    if ((*p == '\0') || (*p == 0xff)) break;
	    if (++p == q) return CS_BAD_TUPLE;
	}
	if ((*p == 0xff) || (++p == q)) break;
    }
    if (found) {
	*found = ns;
	return CS_SUCCESS;
    }
    else {
	if (ns == max)
	    return CS_SUCCESS;
	else
	    return CS_BAD_TUPLE;
    }
} /* parse_strings */

/*====================================================================*/

static int parse_vers_1(tuple_t *tuple, cistpl_vers_1_t *vers_1)
{
    u_char *p, *q;
    
    p = (char *)tuple->TupleData;
    q = p + tuple->TupleDataLen;
    
    vers_1->major = *p; p++;
    vers_1->minor = *p; p++;
    if (p >= q) return CS_BAD_TUPLE;

    return parse_strings(p, q, CISTPL_VERS_1_MAX_PROD_STRINGS,
			 vers_1->str, vers_1->ofs, &vers_1->ns);
} /* parse_vers_1 */

/*====================================================================*/

static int parse_altstr(tuple_t *tuple, cistpl_altstr_t *altstr)
{
    u_char *p, *q;
    
    p = (char *)tuple->TupleData;
    q = p + tuple->TupleDataLen;
    
    return parse_strings(p, q, CISTPL_MAX_ALTSTR_STRINGS,
			 altstr->str, altstr->ofs, &altstr->ns);
} /* parse_altstr */

/*====================================================================*/

static int parse_jedec(tuple_t *tuple, cistpl_jedec_t *jedec)
{
    u_char *p, *q;
    int nid;

    p = (char *)tuple->TupleData;
    q = p + tuple->TupleDataLen;

    for (nid = 0; nid < CISTPL_MAX_DEVICES; nid++) {
	if (p > q-2) break;
	jedec->id[nid].mfr = p[0];
	jedec->id[nid].info = p[1];
	p += 2;
    }
    jedec->nid = nid;
    return CS_SUCCESS;
} /* parse_jedec */

/*====================================================================*/

static int parse_manfid(tuple_t *tuple, cistpl_manfid_t *m)
{
    u_short *p;
    if (tuple->TupleDataLen < 4)
	return CS_BAD_TUPLE;
    p = (u_short *)tuple->TupleData;
    m->manf = p[0];
    m->card = p[1];
    return CS_SUCCESS;
} /* parse_manfid */

/*====================================================================*/

static int parse_funcid(tuple_t *tuple, cistpl_funcid_t *f)
{
    u_char *p;
    if (tuple->TupleDataLen < 2)
	return CS_BAD_TUPLE;
    p = (u_char *)tuple->TupleData;
    f->func = p[0];
    f->sysinit = p[1];
    return CS_SUCCESS;
} /* parse_funcid */

/*====================================================================*/

static int parse_funce(tuple_t *tuple, cistpl_funce_t *f)
{
    u_char *p;
    int i;
    if (tuple->TupleDataLen < 1)
	return CS_BAD_TUPLE;
    p = (u_char *)tuple->TupleData;
    f->type = p[0];
    for (i = 1; i < tuple->TupleDataLen; i++)
	f->data[i-1] = p[i];
    return CS_SUCCESS;
} /* parse_funce */

/*====================================================================*/

static int parse_config(tuple_t *tuple, cistpl_config_t *config)
{
    int rasz, rmsz, i;
    u_char *p;

    p = (char *)tuple->TupleData;
    rasz = *p & 0x03;
    rmsz = (*p & 0x3c) >> 2;
    if (tuple->TupleDataLen < rasz+rmsz+4)
	return CS_BAD_TUPLE;
    config->last_idx = *(++p);
    p++;
    config->base = 0;
    for (i = 0; i <= rasz; i++)
	config->base += p[i] << (8*i);
    p += rasz+1;
    for (i = 0; i < 4; i++)
	config->rmask[i] = 0;
    for (i = 0; i <= rmsz; i++)
	config->rmask[i>>2] += p[i] << (8*(i%4));
    config->subtuples = tuple->TupleDataLen - (rasz+rmsz+4);
    return CS_SUCCESS;
} /* parse_config */

/*======================================================================

    The following routines are all used to parse the nightmarish
    config table entries.
    
======================================================================*/


static u_char *parse_power(u_char *p, u_char *q,
			   cistpl_power_t *pwr)
{
    int i;
    u_long scale;

    if (p == q) return NULL;
    pwr->present = *p;
    pwr->flags = 0;
    p++;
    for (i = 0; i < 7; i++)
	if (pwr->present & (1<<i)) {
	    if (p == q) return NULL;
	    pwr->param[i] = POWER_CVT(*p);
	    scale = POWER_SCALE(*p);
	    while (*p & 0x80) {
		if (++p == q) return NULL;
		if ((*p & 0x7f) < 100)
		    pwr->param[i] += (*p & 0x7f) * scale / 100;
		else if (*p == 0x7d)
		    pwr->flags |= CISTPL_POWER_HIGHZ_OK;
		else if (*p == 0x7e)
		    pwr->param[i] = 0;
		else if (*p == 0x7f)
		    pwr->flags |= CISTPL_POWER_HIGHZ_REQ;
		else
		    return NULL;
	    }
	    p++;
	}
    return p;
} /* parse_power */

/*====================================================================*/

static u_char *parse_timing(u_char *p, u_char *q,
			    cistpl_timing_t *timing)
{
    u_char scale;

    if (p == q) return NULL;
    scale = *p;
    if ((scale & 3) != 3) {
	if (++p == q) return NULL;
	timing->wait = SPEED_CVT(*p);
	timing->waitscale = exponent[scale & 3];
    }
    scale >>= 2;
    if ((scale & 7) != 7) {
	if (++p == q) return NULL;
	timing->ready = SPEED_CVT(*p);
	timing->rdyscale = exponent[scale & 7];
    }
    scale >>= 3;
    if (scale != 7) {
	if (++p == q) return NULL;
	timing->reserved = SPEED_CVT(*p);
	timing->rsvscale = exponent[scale];
    }
    p++;
    return p;
} /* parse_timing */

/*====================================================================*/

static u_char *parse_io(u_char *p, u_char *q, cistpl_io_t *io)
{
    int i, j, bsz, lsz;

    if (p == q) return NULL;
    io->flags = *p;

    if (!(*p & 0x80)) {
	io->nwin = 1;
	io->win[0].base = 0;
	io->win[0].len = (1 << (io->flags & CISTPL_IO_LINES_MASK));
	return p+1;
    }
    
    if (++p == q) return NULL;
    io->nwin = (*p & 0x0f) + 1;
    bsz = (*p & 0x30) >> 4;
    if (bsz == 3) bsz++;
    lsz = (*p & 0xc0) >> 6;
    if (lsz == 3) lsz++;
    p++;
    
    for (i = 0; i < io->nwin; i++) {
	io->win[i].base = 0;
	io->win[i].len = 1;
	for (j = 0; j < bsz; j++, p++) {
	    if (p == q) return NULL;
	    io->win[i].base += *p << (j*8);
	}
	for (j = 0; j < lsz; j++, p++) {
	    if (p == q) return NULL;
	    io->win[i].len += *p << (j*8);
	}
    }
    return p;
} /* parse_io */

/*====================================================================*/

static u_char *parse_mem(u_char *p, u_char *q, cistpl_mem_t *mem)
{
    int i, j, asz, lsz, has_ha;
    u_long len, ca, ha;

    if (p == q) return NULL;

    mem->nwin = (*p & 0x07) + 1;
    lsz = (*p & 0x18) >> 3;
    asz = (*p & 0x60) >> 5;
    has_ha = (*p & 0x80);
    if (++p == q) return NULL;
    
    for (i = 0; i < mem->nwin; i++) {
	len = ca = ha = 0;
	for (j = 0; j < lsz; j++, p++) {
	    if (p == q) return NULL;
	    len += *p << (j*8);
	}
	for (j = 0; j < asz; j++, p++) {
	    if (p == q) return NULL;
	    ca += *p << (j*8);
	}
	if (has_ha)
	    for (j = 0; j < asz; j++, p++) {
		if (p == q) return NULL;
		ha += *p << (j*8);
	    }
	mem->win[i].len = len << 8;
	mem->win[i].card_addr = ca << 8;
	mem->win[i].host_addr = (caddr_t)(ha << 8);
    }
    return p;
} /* parse_mem */

/*====================================================================*/

static u_char *parse_irq(u_char *p, u_char *q, cistpl_irq_t *irq)
{
    if (p == q) return NULL;
    irq->IRQInfo1 = *p; p++;
    if (irq->IRQInfo1 & IRQ_INFO2_VALID) {
	if (p+2 > q) return NULL;
	irq->IRQInfo2 = (p[1]<<8) + p[0];
	p += 2;
    }
    return p;
} /* parse_irq */

/*====================================================================*/

static int parse_cftable_entry(tuple_t *tuple,
			       cistpl_cftable_entry_t *entry)
{
    u_char *p, *q, features;

    p = tuple->TupleData;
    q = p + tuple->TupleDataLen;
    entry->index = *p & 0x3f;
    entry->flags = 0;
    if (*p & 0x40)
	entry->flags |= CISTPL_CFTABLE_DEFAULT;
    if (*p & 0x80) {
	if (++p == q) return CS_BAD_TUPLE;
	if (*p & 0x10)
	    entry->flags |= CISTPL_CFTABLE_BVDS;
	if (*p & 0x20)
	    entry->flags |= CISTPL_CFTABLE_WP;
	if (*p & 0x40)
	    entry->flags |= CISTPL_CFTABLE_RDYBSY;
	if (*p & 0x80)
	    entry->flags |= CISTPL_CFTABLE_MWAIT;
	entry->interface = *p & 0x0f;
    }
    else
	entry->interface = 0;

    /* Process optional features */
    if (++p == q) return CS_BAD_TUPLE;
    features = *p; p++;

    /* Power options */
    if ((features & 3) > 0) {
	p = parse_power(p, q, &entry->vcc);
	if (p == NULL) return CS_BAD_TUPLE;
    }
    else entry->vcc.present = 0;
    if ((features & 3) > 1) {
	p = parse_power(p, q, &entry->vpp1);
	if (p == NULL) return CS_BAD_TUPLE;
    }
    else entry->vpp1.present = 0;
    if ((features & 3) > 2) {
	p = parse_power(p, q, &entry->vpp2);
	if (p == NULL) return CS_BAD_TUPLE;
    }
    else entry->vpp2.present = 0;

    /* Timing options */
    if (features & 0x04) {
	p = parse_timing(p, q, &entry->timing);
	if (p == NULL) return CS_BAD_TUPLE;
    }
    else {
	entry->timing.wait = 0;
	entry->timing.ready = 0;
	entry->timing.reserved = 0;
    }
    
    /* I/O window options */
    if (features & 0x08) {
	p = parse_io(p, q, &entry->io);
	if (p == NULL) return CS_BAD_TUPLE;
    }
    else
	entry->io.nwin = 0;
    
    /* Interrupt options */
    if (features & 0x10) {
	p = parse_irq(p, q, &entry->irq);
	if (p == NULL) return CS_BAD_TUPLE;
    }
    else
	entry->irq.IRQInfo1 = 0;

    switch (features & 0x60) {
    case 0x00:
	entry->mem.nwin = 0;
	break;
    case 0x20:
	entry->mem.nwin = 1;
	entry->mem.win[0].len = (*(u_short *)p) << 8;
	entry->mem.win[0].card_addr = 0;
	entry->mem.win[0].host_addr = NULL;
	p += 2;
	if (p > q) return CS_BAD_TUPLE;
	break;
    case 0x40:
	entry->mem.nwin = 1;
	entry->mem.win[0].len = (*(u_short *)p) << 8;
	entry->mem.win[0].card_addr = (*(u_short *)(p+2)) << 8;
	entry->mem.win[0].host_addr = (caddr_t)entry->mem.win[0].host_addr;
	p += 4;
	if (p > q) return CS_BAD_TUPLE;
	break;
    case 0x60:
	p = parse_mem(p, q, &entry->mem);
	if (p == NULL) return CS_BAD_TUPLE;
	break;
    }

    /* Misc features */
    if (features & 0x80) {
	if (p == q) return CS_BAD_TUPLE;
	if (*p & 0x08)
	    entry->flags |= CISTPL_CFTABLE_AUDIO;
	if (*p & 0x10)
	    entry->flags |= CISTPL_CFTABLE_READONLY;
	if (*p & 0x20)
	    entry->flags |= CISTPL_CFTABLE_PWRDOWN;
	while (*p & 0x80)
	    if (++p == q) return CS_BAD_TUPLE;
	p++;
    }

    entry->subtuples = q-p;
    
    return CS_SUCCESS;
} /* parse_cftable_entry */

/*====================================================================*/

static int parse_device_geo(tuple_t *tuple, cistpl_device_geo_t *geo)
{
    u_char *p, *q;
    int n;

    p = (char *)tuple->TupleData;
    q = p + tuple->TupleDataLen;

    for (n = 0; n < CISTPL_MAX_DEVICES; n++) {
	if (p > q-6) break;
	geo->geo[n].buswidth = p[0];
	geo->geo[n].erase_block = 1 << (p[1]-1);
	geo->geo[n].read_block  = 1 << (p[2]-1);
	geo->geo[n].write_block = 1 << (p[3]-1);
	geo->geo[n].partition   = 1 << (p[4]-1);
	geo->geo[n].interleave  = 1 << (p[5]-1);
	p += 6;
    }
    geo->ngeo = n;
    return CS_SUCCESS;
} /* parse_device_geo */

/*====================================================================*/

static int parse_vers_2(tuple_t *tuple, cistpl_vers_2_t *v2)
{
    u_char *p, *q;

    if (tuple->TupleDataLen < 10)
	return CS_BAD_TUPLE;
    
    p = tuple->TupleData;
    q = p + tuple->TupleDataLen;

    v2->vers = p[0];
    v2->comply = p[1];
    v2->dindex = *(u_short *)(p+2);
    v2->vspec8 = p[6];
    v2->vspec9 = p[7];
    v2->nhdr = p[8];
    p += 9;
    return parse_strings(p, q, 2, v2->str, &v2->vendor, NULL);
} /* parse_vers_2 */

/*====================================================================*/

static int parse_org(tuple_t *tuple, cistpl_org_t *org)
{
    u_char *p, *q;
    int i;
    
    p = tuple->TupleData;
    q = p + tuple->TupleDataLen;
    if (p == q) return CS_BAD_TUPLE;
    org->data_org = *p;
    if (++p == q) return CS_BAD_TUPLE;
    for (i = 0; i < 30; i++) {
	org->desc[i] = *p;
	if (*p == '\0') break;
	if (++p == q) return CS_BAD_TUPLE;
    }
    return CS_SUCCESS;
} /* parse_org */

/*====================================================================*/

int parse_tuple(client_handle_t handle, tuple_t *tuple, cisparse_t *parse)
{
    int ret = CS_SUCCESS;
    
    if (tuple->TupleDataLen > tuple->TupleDataMax)
	return CS_BAD_TUPLE;
    switch (tuple->TupleCode) {
    case CISTPL_DEVICE:
    case CISTPL_DEVICE_A:
	ret = parse_device(tuple, &parse->device);
	break;
    case CISTPL_CHECKSUM:
	ret = parse_checksum(tuple, &parse->checksum);
	break;
    case CISTPL_LONGLINK_A:
    case CISTPL_LONGLINK_C:
	ret = parse_longlink(tuple, &parse->longlink);
	break;
    case CISTPL_LONGLINK_MFC:
	ret = parse_longlink_mfc(tuple, &parse->longlink_mfc);
	break;
    case CISTPL_VERS_1:
	ret = parse_vers_1(tuple, &parse->version_1);
	break;
    case CISTPL_ALTSTR:
	ret = parse_altstr(tuple, &parse->altstr);
	break;
    case CISTPL_JEDEC_A:
    case CISTPL_JEDEC_C:
	ret = parse_jedec(tuple, &parse->jedec);
	break;
    case CISTPL_MANFID:
	ret = parse_manfid(tuple, &parse->manfid);
	break;
    case CISTPL_FUNCID:
	ret = parse_funcid(tuple, &parse->funcid);
	break;
    case CISTPL_FUNCE:
	ret = parse_funce(tuple, &parse->funce);
	break;
    case CISTPL_CONFIG:
	ret = parse_config(tuple, &parse->config);
	break;
    case CISTPL_CFTABLE_ENTRY:
	ret = parse_cftable_entry(tuple, &parse->cftable_entry);
	break;
    case CISTPL_DEVICE_GEO:
    case CISTPL_DEVICE_GEO_A:
	ret = parse_device_geo(tuple, &parse->device_geo);
	break;
    case CISTPL_VERS_2:
	ret = parse_vers_2(tuple, &parse->vers_2);
	break;
    case CISTPL_ORG:
	ret = parse_org(tuple, &parse->org);
	break;
    default:
	ret = CS_UNSUPPORTED_FUNCTION;
	break;
    }
    return ret;
} /* parse_tuple */

/*======================================================================

    This is used internally by Card Services to look up CIS stuff.
    
======================================================================*/

int read_tuple(client_handle_t handle, cisdata_t code, void *parse)
{
    tuple_t tuple;
    cisdata_t buf[255];
    int ret;
    
    tuple.DesiredTuple = code;
    tuple.Attributes = 0;
    ret = CardServices(GetFirstTuple, handle, &tuple, NULL);
    if (ret != CS_SUCCESS) return ret;
    tuple.TupleData = buf;
    tuple.TupleOffset = 0;
    tuple.TupleDataMax = sizeof(buf);
    ret = CardServices(GetTupleData, handle, &tuple, NULL);
    if (ret != CS_SUCCESS) return ret;
    ret = CardServices(ParseTuple, handle, &tuple, parse);
    return ret;
}

/*======================================================================

    This tries to determine if a card has a sensible CIS.  It returns
    the number of tuples in the CIS, or 0 if the CIS looks bad.  The
    checks include making sure several critical tuples are present and
    valid; seeing if the total number of tuples is reasonable; and
    looking for tuples that use reserved codes.
    
======================================================================*/

int validate_cis(client_handle_t handle, cisinfo_t *info)
{
    tuple_t tuple;
    cisparse_t parse;
    int ret, reserved, errors;
    
    if (CHECK_HANDLE(handle))
	return CS_BAD_HANDLE;
    
    info->Chains = reserved = errors = 0;
    tuple.DesiredTuple = RETURN_FIRST_TUPLE;
    tuple.Attributes = 0;
    ret = get_first_tuple(handle, &tuple);
    if (ret != CS_SUCCESS)
	return CS_SUCCESS;

    /* First tuple should be DEVICE */
    if (tuple.TupleCode != CISTPL_DEVICE)
	errors++;
    /* All cards should have a MANFID tuple */
    if (read_tuple(handle, CISTPL_MANFID, &parse) != CS_SUCCESS)
	errors++;
    /* All cards should have either a VERS_1 or a VERS_2 tuple */
    if ((read_tuple(handle, CISTPL_VERS_1, &parse) != CS_SUCCESS) &&
	(read_tuple(handle, CISTPL_VERS_2, &parse) != CS_SUCCESS))
	errors++;
    if (errors > 1)
	return CS_SUCCESS;
    
    for (info->Chains = 1; info->Chains < MAX_TUPLES; info->Chains++) {
	ret = get_next_tuple(handle, &tuple);
	if (ret != CS_SUCCESS) break;
	if (((tuple.TupleCode > 0x23) && (tuple.TupleCode < 0x40)) ||
	    ((tuple.TupleCode > 0x47) && (tuple.TupleCode < 0x80)) ||
	    ((tuple.TupleCode > 0x90) && (tuple.TupleCode < 0xff)))
	    reserved++;
    }
    if ((info->Chains == MAX_TUPLES) || (reserved > 5))
	info->Chains = 0;
    
    return CS_SUCCESS;
} /* validate_cis */

