/*****************************************************************/
/**                                                             **/
/**             (C) Copyright 1992 the Regents of the           **/
/**        University of California.  All Rights Reserved.      **/
/**                                                             **/
/**        This work was produced under the sponsorship of      **/
/**         the U.S. Department of Energy.  The Government      **/
/**                retains certain rights therein.              **/
/**                                                             **/
/**                         Written by                          **/
/**         Distributed Programming Environments Project        **/
/**           Computer Software and Networking Division,        **/
/**                   Livermore Computer Center,                **/
/**            Lawrence Livermore National Laboratory           **/
/**                                                             **/
/*****************************************************************/

/*
	Embedded Language for Remote Operations Services
	ELROS

	AUTHOR:		Robyne M. Sumpter
			Network Systems Division

	DATE WRITTEN:	3/4/90

	ROUTINE:	__ROr_Scan
			__ROr_ISODEScan
			__ROr_ClearSocket
			__ROr_RetrySend
			__ROr_ISODEwait_for_send
			__ROr_Wake_Task
			__ROr_AddSocket
			Hwait

PURPOSE:
	
	The definition/declaration of the structures needed to support tasking.
	__ROr_Scan adds a socket number to the general select mask and 
	  calls AddSocket
	__ROr_ISODEScan adds a socket number to the ISODE asynchronous write
	   select mask and calls AddSocket
	__ROr_ClearSocket removes the task from the __ROv_SocketList.
	__ROr_RetrySend calls TNetAccept to retry the asynchronous sends
	   in ISODE and wakes any tasks that are waiting if the send
	   completes.
	__ROr_ISODEwait_for_send adds the socket to socket list, calls sleep
	   and retries sending until the send completes or timeout occurs.
	__ROr_Wake_Task wakes the task that waiting on socket activity in a 
	specific direction.
	__ROr_AddSocket adds a socket/taskid to the list of tasks waiting on 
	socket activity.
	Hwait  performs the select using the general select mask.  Wakes any
	   tasks waiting on completed events.



IN:

OUT:


CALLED ROUTINES:
	

	
MODIFICATION HISTORY:


*/

#include <elros/instance.h>
#include <elros/exceptions.h>

#ifdef __RO_PLATFORM_ISODE
# include <isode/tsap.h>

static fd_set  __ROv_ISODESendMask;		/* Asynchronous sends */
#endif

#include <sys/time.h>

typedef struct __RO_portdesc_ {
      struct __RO_portdesc_ *forward;
      struct __RO_portdesc_ *backward;
      Task task[3];
      __RO_Instance_Record *instptr;
} *__RO_Port;

static 	fd_set	__ROv_SelectMask[3];
static 	__RO_Port __ROv_SocketList[FD_SETSIZE];
int	__ROv_ISODEListenFileDesc;	

static struct timeval delay = {0, 1};


/* Carry out one step of the determination of the position of the leftmost
 * bit in an integer sized mask containing at least one bit.  This macro is
 * intended to be used repeatedly for successively smaller values of (the
 * log of) the width, beginning with the value just below that corresponding to
 * the largest sized integer among the intended machines and ending with zero.
 * After such repeated use, an O(log sizeof(int)) algorithm, the value of mask
 * should be one and that of shift should be the position.
 *   TAKEN FROM J. FLETCHER'S XPORT.C FOR PADS
 */
/*  macro statement
Bitfind(mask, shift, width)
    unsigned long mask;                    mask being searched
    int shift;                             partial shift of bit being found
    int width;                             log of width */

#   define Bitfind(mask, shift, width) \
    if ((mask) & ~0 << (1<<(width))) { \
        (mask) >>= 1<<(width); \
        (shift) += 1<<(width); \
    }




#ifdef __RO_PLATFORM_ISODE

    int __ROr_ISODEScan( sockno, inst )
	int sockno;
	__RO_Instance_Record *inst;
	{

	   FD_SET( sockno, &(__ROv_ISODESendMask) );
 	   return(__ROr_AddSocket( sockno, __ROm_WRITEDIR, inst ));
   	}



    int __ROr_ISODEwait_for_send(instance)
       __RO_Instance_Record *instance;
    {
	int done = 0;
	int status = 0;
	int absolute_timeout;

         if(__ROr_ISODEScan(instance->subsystem->specific.isode.association,
			    instance  ))
            return(EXCEPTION);

        if((status = __ROr_RetrySend(
                    instance->subsystem->specific.isode.association)) != -1 )
        {
 
	    __ROr_ClearSocket(instance->subsystem->specific.isode.association,
				__ROm_WRITEDIR);

            if( status == EXCEPTION )
                return(EXCEPTION);
 
            absolute_timeout = __ROr_STDget_absolute_timeout(instance);

            while( !done )
            {

               __ROr_ISODEScan(instance->subsystem->specific.isode.association,
			       instance );

               Alarm( absolute_timeout );
               SLEEP;

               if( TIME > absolute_timeout )
                   __RO_RETURN_RUNTIME(instance,__ROx_SEND_TIMEOUT_ISODE );
               done = 1;

	      __ROr_ClearSocket(instance->subsystem->specific.isode.association,
				__ROm_WRITEDIR);
                
            }
        }
	else
	    SLEEP;		/* Clear hyper state */
	return (0);
   }
#endif




    int Add_descriptor( sockno, dir )
	int sockno;
	int dir;
	{

 	   return(__ROr_Scan( sockno, dir, NULL));
   	}



    int __ROr_Scan( sockno, dir, inst )
	int sockno;
	int dir;
	__RO_Instance_Record *inst;
	{

	   FD_SET( sockno, (__ROv_SelectMask+dir) );
 	   return(__ROr_AddSocket( sockno, dir, inst));
   	}




    int __ROr_ClearSocket( sockno, direction )
    int sockno;
    int direction;
    {
	
	if( __ROv_SocketList[sockno]->task[direction] )
	{
	     __ROv_SocketList[sockno]->task[direction] = (Task)Null;
 	}	

		/*
		 * If there are no tasks waiting on this socket, make sure
		 * the instance pointer is cleared 
		 */
	if( (__ROv_SocketList[sockno]->task[0] == (Task)Null) &&
	    (__ROv_SocketList[sockno]->task[1] == (Task)Null) &&
	    (__ROv_SocketList[sockno]->task[2] == (Task)Null)   )
	    __ROv_SocketList[sockno]->instptr = (__RO_Instance_Record *)Null;


	return 0;
    }




    int __ROr_AddSocket( sockno, direction, inst )
    int sockno;
    int direction;
    __RO_Instance_Record *inst;
    {

	if( !(__ROv_SocketList[sockno] ) )
	{
	   __ROv_SocketList[sockno] = (__RO_Port)malloc(sizeof(struct __RO_portdesc_));
	   if( !(__ROv_SocketList[sockno]) )
	   {
	      if (inst)
              {
                 __ROinternal_EXCEPTION(inst,__ROx_TASK_OUTOFMEM);
              }
	      return( EXCEPTION );
	   }
	   memset( __ROv_SocketList[sockno], 0, sizeof(struct __RO_portdesc_) );
 	   __ROv_SocketList[sockno]->task[direction] = Ego();
 	   __ROv_SocketList[sockno]->instptr = inst;
	   __ROv_SocketList[sockno]->forward = (struct __RO_portdesc_ *)Null;
	   __ROv_SocketList[sockno]->backward = (struct __RO_portdesc_ *)Null;
        }
	else
	{
			/*
			 * There is possibly more than one task waiting
			 * on the socket in the same direction.  This
			 * should only happen on the listen socket.
			 */
	   if( __ROv_SocketList[sockno]->task[direction] != (Task)Null )
	   {
	       __RO_Port port;
	       __RO_Port newport;

				/*  Get a new port structure */
	       newport = (__RO_Port)malloc(sizeof(struct __RO_portdesc_));
	       if( !newport )
	       {
	          __ROinternal_EXCEPTION(inst,__ROx_TASK_OUTOFMEM);
	          return( EXCEPTION );
	       }
	       memset( newport, 0, sizeof(struct __RO_portdesc_) );
	       

	       port = __ROv_SocketList[sockno];
	       while( port->forward )
	      	   port = port->forward;

	       port->forward = (__RO_Port)newport; 
	       newport->backward = (__RO_Port)port;
	       newport->task[direction] = Ego();
	       newport->instptr = inst;
	   }
	   else
	   {
				/*
				 * The port structure exists but there is
				 * only one task waiting on any direction.
				 */
 	       __ROv_SocketList[sockno]->task[direction] = Ego();
 	       __ROv_SocketList[sockno]->instptr = inst;
	   }
	}
	return (0);
    }



   int __ROr_RetrySend(fd)
       int fd;			
   {
#ifdef __RO_PLATFORM_ISODE
      fd_set mask;
      char *argvec[4];
      int  veclen;
      int  direction;
      int  bit;
      int  sockno;
      int  status;
      unsigned int submask;
      struct TSAPdisconnect tdisconnect;

      memset( &mask, 0, sizeof(mask));
      memcpy(&mask, &__ROv_ISODESendMask, sizeof(mask));
      status = TNetAccept( &veclen, argvec, FD_SETSIZE, (char *)Null, 
			   &mask, (char *)Null, OK, &tdisconnect );
      if( status == NOTOK )
      {
	return(EXCEPTION);
      }

      				/*
				 * Determine if any sends completed
				 * and wake up the corresponding tasks
				 * if they are waiting on the event.
				 */
	 status = 0;
         direction = 0;		/* Send direction only */

	
	 for( bit = 0; bit < sizeof(fd_set)/sizeof(long); bit ++ )
	    for( ((long *)&(__ROv_ISODESendMask))[bit] &= 
			 ~((long *)&(mask))[bit];
		 submask = ((long *)&(mask))[bit]; )
	    {
		sockno = bit * (sizeof(long));
                if (sizeof(long) > 4)
		   Bitfind( submask, sockno, 5 ); 
		Bitfind( submask, sockno, 4 ); 
		Bitfind( submask, sockno, 3 ); 
		Bitfind( submask, sockno, 2 ); 
		Bitfind( submask, sockno, 1 ); 
		Bitfind( submask, sockno, 0 ); 

 		((long *)&(mask))[bit] &= ~(submask<<sockno);

		if( submask != 1 || !(__ROv_SocketList[sockno]) )
		    continue;

		__ROr_Wake_Task( sockno, direction, 0, (char **)Null );
	       
			/*
			 * If the fd passed in has activity, return a 
			 * true value to the caller.  If the caller is not
			 * interested in a specific socket, the fd is -1.
		 	 * This is for the immediate retry on each send to
			 * to indicate the send was successful.
			 */
		if( sockno == fd )
		   status = -1;

	    }

	return status;

#endif
   }


int __ROr_Wake_Task(sockno, dir, veclen, argvec )
    int sockno;
    int dir;
    int veclen;
    char *argvec[__ROc_ARGVECSIZE];
{

   __RO_Port port;

   port = __ROv_SocketList[sockno];
   while( port )
   {
       if( port->task[dir] )
       {
	  Wake(port->task[dir] );
#ifdef __RO_PLATFORM_ISODE
		/* If this is a new connection save the new socket num */
	  if( sockno == __ROv_ISODEListenFileDesc )
          {
             port->instptr->subsystem->specific.isode.vectorlength = veclen;
             memcpy(port->instptr->subsystem->specific.isode.argvector, 
		argvec, (sizeof( *argvec ) * __ROc_ARGVECSIZE) );
          }
#endif
	  port->task[dir] = (Task)Null;
	  port->instptr = (__RO_Instance_Record *)Null;
	  break;
       }
       else
	  port = port->forward;
   }

		/*
		 * See if there are other tasks waiting on this socket in
		 * dir direction.  If so add the socket to the select mask
		 * again.  It was cleared in Hwait. Start with the current
		 * port.
		 */
  while(port)
  {
     if( port->forward && port->forward->task[dir] )
     {
	FD_SET( sockno, __ROv_SelectMask+dir);
	break;
    }
     port = port->forward;
  }

}




/* Wait for external communication events but not beyond time limit; then
 * wake tasks waiting for events that have occurred.  The microsecond field
 * in the time delay structure is also used as a flag to indicate that a
 * file descriptor may have been selected asynchronously (e. g., in an
 * interrupt routine) and that therefore any delay should be inhibited so that
 * waiting for activity on that descriptor can also take place (during  the
 * next call).
 */
    void
Hwait (timlim)
    unsigned int timlim;                /* time limit */
{
    unsigned int now = time(0);         /* current time */
#   define delmax (24*60*60)            /* maximum delay */
    fd_set mask[3];                     /* select masks */
    int d;                              /* index of mask */
    int j;                              /* index of submask of mask */
    unsigned int submask;               /* submask */
    int n;                              /* selected socket # */
 

    delay.tv_sec = timlim > now ? timlim - now : 0;
    if ((unsigned int) delay.tv_sec > delmax)
        delay.tv_sec = delmax;
 
    /* Inhibit delay if so flagged; clear microsecond field. */
    if (delay.tv_usec == 0)
        delay.tv_sec = 0;
    else
        delay.tv_usec = 0;
 
    /* Wait for socket activity; then clear masks if error. */
    memcpy(mask, __ROv_SelectMask, sizeof mask);

#ifdef __RO_PLATFORM_ISODE
    /* OR in the asynchronous writes so we don't block if there's work to do */
    for( j=0; j<sizeof(fd_set)/sizeof(int); j++)
        ((int *)(mask+__ROm_WRITEDIR))[j] |= ((int *)&__ROv_ISODESendMask)[j];
#endif

    if (select(FD_SETSIZE, mask+1, mask+0, mask+2, &delay) < 0)
        memset(mask, 0, sizeof mask);
 
       
    /* Handle send, recv, error masks (broken into submasks) for all sockets */
    for (d = 2; d >= 0; d--)
        for (j = 0; j < sizeof(fd_set)/sizeof(long); j++)
            for (((long *) (__ROv_SelectMask+d))[j] &= ~((long *) (mask+d))[j];
                    submask = ((long *) (mask+d))[j]; ) 
            {
 
                /* Compute the socket # (bit position); clear it from mask. */
                n = j*(sizeof(long));
                if (sizeof(long) > 4)
                   Bitfind(submask, n, 5)
                Bitfind(submask, n, 4)
                Bitfind(submask, n, 3)
                Bitfind(submask, n, 2)
                Bitfind(submask, n, 1)
                Bitfind(submask, n, 0)
                ((long *) (mask+d))[j] &= ~(submask<<n);

 
                /* Get port id (ptr to state); if none, ignore. */
                if (submask != 1 
                        || !(__ROv_SocketList[n]))
                    continue;
 
		/* If the fd is in error and this is an elros fd,
		 * raise exception in the instance.
		 */ 
		if( d == 2 )
		{
		  if( __ROv_SocketList[n]->instptr )
		     __ROinternal_EXCEPTION(__ROv_SocketList[n]->instptr,
						  __ROx_TASK_FDERROR );
		}


                /* Wake waiting task. Listens get awakened by
		 * block of code below.
		 */
#ifdef __RO_PLATFORM_ISODE
		if( n != __ROv_ISODEListenFileDesc )
#endif
  	           __ROr_Wake_Task( n, d, 0, (char **)Null );
            }

#ifdef __RO_PLATFORM_ISODE
				/*
				 * Check if a new connection has arrived on the
				 * Listen File Descriptor, use TNetAccept
				 * to accept the connection.
				 */
	    {
		    int veclen,
			numfds = FD_SETSIZE,
			connection_desc;
		    struct TSAPaddr taddr;
		    struct TSAPdisconnect tdisconnect;
		    struct PSAPstart presentation_start;
		    struct PSAPindication pindication;
		    char *argvec[__ROc_ARGVECSIZE];
		    fd_set readmask, writemask, errormask;
		    int status;
		    
		    memset( &readmask, 0, sizeof(fd_set));
		    memset( &writemask, 0, sizeof(fd_set));
		    memset( &errormask, 0, sizeof(fd_set));

			/*
			 * Call TNetAccept at least twice to see is a 
			 * connection has been previously partially accepted.
			 */
		    status = TNetAcceptAux( &veclen, argvec, &connection_desc,
					    &taddr, numfds, &readmask,
					    &writemask, &errormask, 0,
					    &tdisconnect);
		    if( veclen > 0 )
		    {

				/*
				 * Find a task that is waiting on the listen
				 * file descriptor, put the new socket number
				 * in it's instance record and wake the task.
				 */
		      __ROr_Wake_Task( __ROv_ISODEListenFileDesc, 
				       __ROm_READDIR, veclen,
				       argvec  );	
		    }
		    else
			  if( connection_desc > 0 )
			     FD_SET( connection_desc, 
				    __ROv_SelectMask+__ROm_READDIR); 
	
	
		    while(1)
		    {
	
		       status = TNetAcceptAux( &veclen, argvec, &connection_desc,
						&taddr, numfds, &readmask,
						&writemask, &errormask, 0,
						&tdisconnect);
		      if( veclen <= 0 )
		      {
			  int fd;

			  
			  if( connection_desc > 0 )
			     FD_SET( connection_desc, 
					__ROv_SelectMask+__ROm_READDIR ); 

			  break;
	 	      }
				
				/*
				 * Find a task that is waiting on the listen
				 * file descriptor, put the new socket number
				 * in it's instance record and wake the task.
				 */
		      __ROr_Wake_Task(__ROv_ISODEListenFileDesc, __ROm_READDIR,
				      veclen, argvec  );	

		    }
		}
#endif


     __ROr_RetrySend(-1);

 
    /* Reenable delay. */
    delay.tv_usec = 1;
    return;
}

