/*
 * Copyright (c) 1995, 1996, 1997, 1998 Kungliga Tekniska Högskolan
 * (Royal Institute of Technology, Stockholm, Sweden).
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *      This product includes software developed by the Kungliga Tekniska
 *      Högskolan and its contributors.
 * 
 * 4. Neither the name of the Institute nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <xfs_common.h>

#include <xfs_message.h>
#include <xfs_dev.h>
#include <xfs_fs.h>
#include <nxfs.h>
#include <xdeb.h>

/*
 * Queues of xfs_links hold outbound messages and processes sleeping
 * for replies. The last field is used to return errno to sleepers and
 * to keep record of memory to be deallocated when messages have been
 * delivered or dropped.
 */
struct xfs_link {
  struct xfs_link *prev, *next;
  struct xfs_message_header *message;
  u_int errno_or_size;		/* errno on sleepq and size on messageq */
};  

struct xfs_channel {
  dev_info_t *dip;
  struct xfs_link messageq;	/* Messages not yet read */
  struct xfs_link sleepq;	/* Waiting for reply message */
  u_int nsequence;
  struct pollhead pollhead;
  struct proc *selecting_proc;
  struct xfs_message_header *message_buffer;
  int status;
#define CHANNEL_OPENED	0x1
};

static void *xfs_dev_state;

static void
xfs_initq(struct xfs_link *q)
{
  q->next = q;
  q->prev = q;
}

/* Is this queue empty? */
#define xfs_emptyq(q) ((q)->next == (q))

/* Is this link on any queue? Link *must* be inited! */
#define xfs_onq(link) ((link)->next != 0 || (link)->prev != 0)

/* Append q with p */
static void
xfs_appendq(struct xfs_link *q, struct xfs_link *p)     
{
  p->next = q;
  p->prev = q->prev;
  p->prev->next = p;
  q->prev = p;
}

static void
xfs_outq(struct xfs_link *p)     
{
  p->next->prev = p->prev;
  p->prev->next = p->next;
  p->next = p->prev = 0;
}

/*
 * Only allow one open.
 */
int
xfs_devopen(dev_t *devp, int flags, int otyp, cred_t *credp)
{
  struct xfs_channel *chan;

  XFSDEB(XDEBDEV, ("xfs_devopen dev = %d, flags = %d, otyp = %d\n",
		   *devp, flags, otyp));

  if (otyp != OTYP_CHR)
      return EINVAL;

  chan = (struct xfs_channel *)ddi_get_soft_state(xfs_dev_state, getminor(*devp));
  if (chan == NULL)
      return ENXIO;

  /* Only allow one reader/writer */
  if (chan->status & CHANNEL_OPENED)
    return EBUSY;
  else
    chan->status |= CHANNEL_OPENED;

  chan->message_buffer = xfs_alloc(MAX_XMSG_SIZE);

  return 0;
}

/*
 * Wakeup all sleepers and cleanup.
 */
int
xfs_devclose(dev_t dev, int flags, int otyp, cred_t *credp)
{
  struct xfs_channel *chan;
  struct xfs_link *first;

  XFSDEB(XDEBDEV, ("xfs_devclose dev = %d, flags = %d, otyp = %d\n",
		   dev, flags, otyp));

  chan = (struct xfs_channel *)ddi_get_soft_state(xfs_dev_state, getminor(dev));
  if (chan == NULL)
      return ENXIO;

  /* Sanity check, paranoia? */
  if (!(chan->status & CHANNEL_OPENED))
    panic("xfs_devclose never opened?");

  chan->status &= ~CHANNEL_OPENED;

  /* No one is going to read those messages so empty queue! */
  while (!xfs_emptyq(&chan->messageq)) {
      XFSDEB(XDEBDEV, ("before outq(messageq)\n"));
      first = chan->messageq.next;
      xfs_outq(first);
      if (first->errno_or_size != 0)
	xfs_free(first, first->errno_or_size);
      XFSDEB(XDEBDEV, ("after outq(messageq)\n"));
  }

  /* Wakeup those waiting for replies that will never arrive. */
  while (!xfs_emptyq(&chan->sleepq)) {
      XFSDEB(XDEBDEV, ("before outq(sleepq)\n"));
      first = chan->sleepq.next;
      xfs_outq(first);
      first->errno_or_size = ENODEV;
      wakeup((caddr_t) first);
      XFSDEB(XDEBDEV, ("after outq(sleepq)\n"));
  }
  
  if (chan->message_buffer) {
      xfs_free(chan->message_buffer, MAX_XMSG_SIZE);
      chan->message_buffer = 0;
  }
      
  /* Free all xfs_nodes. */
  free_all_xfs_nodes(&xfs[getminor(dev)]);
  return 0;
}

/*
 * Move messages from kernel to user space.
 */
int
xfs_devread(dev_t dev, struct uio *uiop, cred_t *credp)
{
  struct xfs_channel *chan;
  struct xfs_link *first;
  int errno;

  XFSDEB(XDEBDEV, ("xfs_devread dev = %d\n", dev));

  chan = (struct xfs_channel *)ddi_get_soft_state(xfs_dev_state, getminor(dev));
  if (chan == NULL)
      return ENXIO;

  if (xfs_emptyq(&chan->messageq))
    return 0;			/* Nothing to read */
  
  /* Remove message */
  first = chan->messageq.next;
  xfs_outq(first);
  errno = uiomove((caddr_t) first->message,
		  first->message->size, UIO_READ, uiop);
  if (first->errno_or_size != 0)
    xfs_free(first, first->errno_or_size);
  return errno;
}

/*
 * Move messages from user space to kernel space,
 * wakeup sleepers, insert new data in VFS.
 */
int
xfs_devwrite(dev_t dev, struct uio *uiop, cred_t *credp)
{
  struct xfs_channel *chan;
  int error;

  XFSDEB(XDEBDEV, ("xfs_devwrite dev = %d\n", dev));

  chan = (struct xfs_channel *)ddi_get_soft_state(xfs_dev_state, getminor(dev));
  if (chan == NULL)
      return ENXIO;

  error = uiomove((caddr_t) chan->message_buffer,
		  MAX_XMSG_SIZE, UIO_WRITE, uiop);
  if (error != 0)
    return error;
  
  /*
   * This thread handles the received message.
   */
  return xfs_message_receive(getminor(dev),
			     chan->message_buffer,
			     chan->message_buffer->size);
}

/*
 * Not used.
 */
int
xfs_devioctl(dev_t dev, int cmd, int arg, int mode, cred_t *credp,
	     int *rvalp)
{
  XFSDEB(XDEBDEV, ("xfs_devioctl dev = %d, cmd = %d\n", dev, cmd));
  return EINVAL;
}

/*
 * Are there any messages on this filesystem?
 */
int
xfs_chpoll(dev_t dev, short events, int anyyet,
	   short *reventsp, struct pollhead **phpp)
{
  struct xfs_channel *chan;

  XFSDEB(XDEBDEV, ("xfs_devselect dev = %d, events = %d, anyyet = %d\n",
		   dev, events, anyyet));

  chan = (struct xfs_channel *)ddi_get_soft_state(xfs_dev_state, getminor(dev));
  if (chan == NULL)
      return ENXIO;

  if (!(events & POLLRDNORM))
      return 0;

  if (!xfs_emptyq(&chan->messageq)) {
      *reventsp |= POLLRDNORM;
  } else {
      *reventsp = 0;
      if (!anyyet)
	  *phpp = &chan->pollhead;
  }
  return 0;
}

/*
 * Send a message to user space.
 */
int
xfs_message_send(int fd, struct xfs_message_header *message, u_int size)
{
  struct xfs_channel *chan;
  struct {
    struct xfs_link this_message;
    struct xfs_message_header msg;
  } *t;

  chan = (struct xfs_channel *)ddi_get_soft_state(xfs_dev_state, fd);
  if (chan == NULL)
      return ENXIO;

  XFSDEB(XDEBMSG, ("xfs_message_send opcode = %d\n", message->opcode));

  if (!(chan->status & CHANNEL_OPENED))	/* No receiver? */
    return ENODEV;
  
  /* Prepare message and copy it later */
  message->size = size;
  message->sequence_num = chan->nsequence++;

  t = xfs_alloc(sizeof(t->this_message) + size);
  t->this_message.errno_or_size = sizeof(t->this_message) + size;
  bcopy(message, &t->msg, size);

  t->this_message.message = &t->msg;
  xfs_appendq(&chan->messageq, &t->this_message);
  pollwakeup(&chan->pollhead, POLLRDNORM);
  return 0;
}

/*
 * Send a message to user space and wait for reply.
 */
int
xfs_message_rpc(int fd, struct xfs_message_header *message, u_int size)
{
  struct xfs_channel *chan;
  struct xfs_link this_message;
  struct xfs_link this_process;

  chan = (struct xfs_channel *)ddi_get_soft_state(xfs_dev_state, fd);
  if (chan == NULL)
      return ENXIO;

  XFSDEB(XDEBMSG, ("xfs_message_rpc opcode = %d\n", message->opcode));

  if (!(chan->status & CHANNEL_OPENED))	/* No receiver? */
    return ENODEV;
  
  if (size < sizeof(struct xfs_message_wakeup)) {
      printf("XFS PANIC Error: Message to small to receive wakeup, opcode = %d\n", message->opcode);
      return ENOMEM;
  }

  message->size = size;
  message->sequence_num = chan->nsequence++;
  this_message.errno_or_size = 0;
  this_message.message = message;
  this_process.message = message;
  xfs_appendq(&chan->messageq, &this_message);
  xfs_appendq(&chan->sleepq, &this_process);
  pollwakeup(&chan->pollhead, POLLRDNORM);
  this_process.errno_or_size = 0;
  if (sleep((caddr_t) &this_process, (PZERO + 1)|PCATCH)) {
      XFSDEB(XDEBMSG, ("caught signal\n"));
      this_process.errno_or_size = EINTR;
  }
  /*
   * Caught signal, got reply message or device was closed.
   * Need to clean up both messageq and sleepq.
   */
  if (xfs_onq(&this_message)) {
      xfs_outq(&this_message);
  }
  if (xfs_onq(&this_process)) {
      xfs_outq(&this_process);
  }
  return this_process.errno_or_size;
}

/*
 * For each message type there is a message handler
 * that implements its action, xfs_message_receive
 * invokes the correct function.
 */
int
xfs_message_receive(int fd, struct xfs_message_header *message, u_int size)
{
  XFSDEB(XDEBMSG, ("xfs_message_receive opcode = %d\n", message->opcode));

  /* Dispatch and coerce message type */
  switch (message->opcode) {
  case XFS_MSG_WAKEUP:
    return xfs_message_wakeup(fd, (struct xfs_message_wakeup *) message, message->size);
  case XFS_MSG_INSTALLROOT:
    return xfs_message_installroot(fd, (struct xfs_message_installroot *) message, message->size);
  case XFS_MSG_INSTALLNODE:
    return xfs_message_installnode(fd, (struct xfs_message_installnode *) message, message->size);
  case XFS_MSG_INSTALLATTR:
    return xfs_message_installattr(fd, (struct xfs_message_installattr *) message, message->size);
  case XFS_MSG_INSTALLDATA:
    return xfs_message_installdata(fd, (struct xfs_message_installdata *) message, message->size);
  case XFS_MSG_INVALIDNODE:
    return xfs_message_invalidnode(fd, (struct xfs_message_invalidnode *) message, message->size);
  default:
    printf("XFS PANIC Warning xfs_dev: Unknown message opcode == %d\n", message->opcode);
    return EINVAL;
  }
}

int
xfs_message_wakeup(int fd, struct xfs_message_wakeup *message, u_int size)
{
  struct xfs_channel *chan;
  struct xfs_link *sleepq = &chan->sleepq;
  struct xfs_link *t = chan->sleepq.next; /* Really first in q */

  chan = (struct xfs_channel *)ddi_get_soft_state(xfs_dev_state, fd);
  if (chan == NULL)
      return ENXIO;

  XFSDEB(XDEBMSG, ("xfs_message_wakeup\n"));

  for (; t != sleepq; t = t->next)
    if (t->message->sequence_num == message->sleepers_sequence_num)
      {
	if (t->message->size < size)
	  {
	    printf("XFS PANIC Error: Could not wakeup requestor with opcode = %d properly, to small receive buffer.\n", t->message->opcode);
	    t->errno_or_size = ENOMEM;
	  }
	else
	  bcopy(message, t->message, size);
	wakeup((caddr_t) t);
	break;
      }

  return 0;
}

int
xfs_dev_init(void)
{
    int ret;

    ret = ddi_soft_state_init(&xfs_dev_state,
			      sizeof(struct xfs_channel), NXFS);

    return ret;
}

int
xfs_dev_fini(void)
{
    ddi_soft_state_fini(&xfs_dev_state);
    return 0;
}

static int
xfs_dev_getinfo(dev_info_t *dip,
		ddi_info_cmd_t infocmd,
		void *arg,
		void **result)
{
    int ret;

    printf ("xfs_dev_getinfo\n");

    switch(infocmd) {
    case DDI_INFO_DEVT2INSTANCE : {
	dev_t dev = (dev_t)arg;
	*result = (void *)getminor(dev);
	ret = DDI_SUCCESS;
	break;
    }
    case DDI_INFO_DEVT2DEVINFO : {
	dev_t dev = (dev_t)arg;
	int instance = getminor(dev);
	struct xfs_channel *chan;

	chan = (struct xfs_channel *)ddi_get_soft_state(xfs_dev_state,
							getminor(dev));

	if (chan == NULL) {
	    *result = NULL;
	    ret = DDI_FAILURE;
	} else {
	    *result = chan->dip;
	    ret = DDI_SUCCESS;
	}
	break;
    }
    default :
	ret = DDI_FAILURE;
	break;
    }
    return ret;
}

static int
xfs_dev_attach(dev_info_t *dip,
	       ddi_attach_cmd_t cmd)
{
    int ret;

    printf ("xfs_dev_attach\n");

    switch(cmd) {
    case DDI_ATTACH : {
	int instance = ddi_get_instance(dip);
	struct xfs_channel *state;

	ret = ddi_soft_state_zalloc(xfs_dev_state, instance);
	if (ret != DDI_SUCCESS)
	    break;
	state = (struct xfs_channel *)ddi_get_soft_state(xfs_dev_state,
							 instance);

	ret = ddi_create_minor_node(dip, "", S_IFCHR, instance, NULL, 0);
	if (ret != DDI_SUCCESS) {
	    ddi_soft_state_free(xfs_dev_state, instance);
	    break;
	}
	
	state->dip = dip;
	xfs_initq(&state->messageq);
	xfs_initq(&state->sleepq);
	state->nsequence = 0;
	state->selecting_proc = NULL;
	state->message_buffer = 0;
	state->status = 0;
	/* how is the pollhead supposed to be initialized? */
	bzero(&state->pollhead, sizeof(state->pollhead));

	ddi_report_dev(dip);
	ret = DDI_SUCCESS;
	break;
    }	
#ifdef DDI_PM_RESUME
    case DDI_PM_RESUME :
#endif
    case DDI_RESUME :
	ret = DDI_SUCCESS;
	break;
    default :
	ret = DDI_FAILURE;
	break;
    }
    return ret;
}

static int
xfs_dev_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
{
    int ret;

    printf ("xfs_dev_detach\n");

    switch (cmd) {
    case DDI_DETACH : {
	int instance = ddi_get_instance(dip);
	struct xfs_channel *state;

	state = (struct xfs_channel *)ddi_get_soft_state(xfs_dev_state,
							 instance);
	ddi_remove_minor_node(dip, NULL);
	ddi_soft_state_free(xfs_dev_state, instance);
	ret = DDI_SUCCESS;
	break;
    }
    case DDI_PM_SUSPEND :
    case DDI_SUSPEND :
	ret = DDI_SUCCESS;
	break;
    default :
	ret = DDI_FAILURE;
	break;
    }
    return ret;
}

static struct cb_ops xfs_cb_ops = {
    nodev,			/* open */
    nodev,			/* close */
    nodev,			/* strategy */
    nodev,			/* print */
    nodev,			/* dump */
    nodev,			/* read */
    nodev,			/* write */
    nodev,			/* ioctl */
    nodev,			/* devmap */
    nodev,			/* mmap */
    nodev,			/* segmap */
    nodev,			/* chpoll */
    nodev,			/* prop_op */
    NULL,			/* cb_str */
    D_NEW,			/* flag */
    0,				/* rev */
    nodev,			/* aread */
    nodev			/* awrite */
};

static struct dev_ops xfs_dev_ops = {
    DEVO_REV,			/* rev */
    0,				/* refcnt */
    xfs_dev_getinfo,		/* getinfo */
    nulldev,			/* identify */
    nulldev,			/* probe */
    xfs_dev_attach,		/* attach */
    xfs_dev_detach,		/* detach */
    nodev,			/* reset */
    &xfs_cb_ops,		/* cb_ops */
    NULL,			/* bus_ops */
    NULL			/* power */
};

struct modldrv xfs_modldrv = {
    &mod_driverops,
    "xfs cdev driver",
    &xfs_dev_ops
};
