/*****************************************************************/
/**                                                             **/
/**             (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           **/
/**                                                             **/
/*****************************************************************/

static char sccsid_ISODEunbind[] = "@(#)ISODEunbind.c	1.9 11/13/92 11:05:31  LLNL ";

/*
	Embedded Language for Remote Operations Services
	ELROS

	AUTHOR:		James A. Guse
			Robyne M. Sumpter
			Network Systems Division

	DATE WRITTEN:	7/25/90

	ROUTINE:	unbind
	Version:	__ROr_STDunbind

PURPOSE:
	This routine unbinds the instance

IN:
	instance - pointer to instance record.

OUT:
	instance - All fields are inaccessible -- pointer is freed.


CALLED ROUTINES:
	

	
MODIFICATION HISTORY:


*/


#include <signal.h>
#include <elros/instance.h>
#include <elros/binds.h>
#include <elros/specifics.h>

#ifdef __RO_PLATFORM_ISODE
#   include <isode/psap2.h>
#   include <isode/pepsy/ACS-types.h>
/*
#   include <isode/../psap2/PS-types.h>
*/
#   include <isode/ppkt.h>




static int  doFINISH (pb, sf, pi)
register struct psapblk *pb;
register struct SSAPfinish *sf;
struct PSAPindication *pi;
{
    int     result;
    register struct PSAPfinish *pf = &pi -> pi_finish;

    pi -> pi_type = PI_FINISH;

    result = ssdu2info (pb, pi, sf -> sf_data, sf -> sf_cc, pf -> pf_info,
                &pf -> pf_ninfo, "P-RELEASE user-data", PPDU_NONE);

    SFFREE (sf);

    if (result == NOTOK)
        return NOTOK;

    pb -> pb_flags |= PB_FINN;
 
    return DONE;
}

int __ROr_free_scatter(instance)

    __RO_Instance_Record *instance;

{

   int i;

   for( i = 0; i < instance->subsystem->specific.isode.uvindex; i++ )
     if( instance->subsystem->specific.isode.uvarray[i].uv_base )
        free(instance->subsystem->specific.isode.uvarray[i].uv_base);

   free( instance->subsystem->specific.isode.uvarray );

   return(SUCCESS);
}



int __ROr_unbind_ISODE( instance )

   __RO_Instance_Record *instance;

{


   if( instance->subsystem->role == Initiator )
   {
      PE user_data; 
      int user_data_length;
      struct PSAPrelease presentation_release_state;
      struct PSAPindication presentation_indication;
      unsigned int absolute_timeout;
      int timeout;
   
#ifdef __RO_TASKING
       /* If tasking, set the timeout for non-blocking (polling) i/o */
       timeout = OK;
#else
       timeout = __ROr_STDget_timeout(instance);
#endif

  			/*
			 * Encode the user data in the release request pdu
			 */
       {
          struct type_ACS_RLRQ__apdu rlrq_apdu;

          memset(&rlrq_apdu,0,sizeof(rlrq_apdu));
          rlrq_apdu.optionals = opt_ACS_RLRQ__apdu_reason;
          rlrq_apdu.reason = int_ACS_reason_normal;
          rlrq_apdu.user__information = NULL;

          if (encode_ACS_RLRQ__apdu(&user_data,1,0,NULLCP,&rlrq_apdu) == NOTOK)
	     __RO_RETURN_RUNTIME(instance,__ROx_BIND_RLRQAPDUENCODE);

          user_data->pe_context = instance->ISO_Contexts.acse_pcid;
          user_data_length = 1;
       }
    

			/* Set absolute timeout for release request */
       absolute_timeout = __ROr_STDget_absolute_timeout(instance);

			/*
			 * Make the release request.
			 */
       if( PRelRequest( instance->subsystem->specific.isode.association,
   	             &user_data,user_data_length,
		     timeout,
		     &presentation_release_state,
		     &presentation_indication) == NOTOK)
      {
         int reason = presentation_indication.pi_abort.pa_reason;

         PAFREE(&presentation_indication.pi_abort);

#ifndef __RO_TASKING

	   __RO_RETURN_RUNTIME( instance, __ROx_BIND_PRELREQUEST );

#else
           if( reason != PC_TIMER )
              __RO_RETURN_RUNTIME(instance,__ROx_BIND_PRELREQUEST)
           else
	   {
	     
		int done = 0;

				/*
				 * Register the socket and taskid 
				 * for both sending and recieving and
				 * wait for the event to occur on the
				 * socket.
				 */
		while( !done )
		{
	            __ROr_ISODEScan(instance->subsystem->specific.isode.association,
				    instance );
	            __ROr_Scan( instance->subsystem->specific.isode.association,
			         __ROm_READDIR, instance );

		    Alarm( absolute_timeout );
	            SLEEP;
	      	    if( TIME > absolute_timeout  )
		        __RO_RETURN_RUNTIME( instance, __ROx_BIND_RELREQTIMEOUT )


				/*
				 * Retry the release request
				 */
		    if( PRelRetryRequest(
		          instance->subsystem->specific.isode.association,
                          0, &presentation_release_state,
                          &presentation_indication) == NOTOK )
		    {
		        if( presentation_indication.pi_abort.pa_reason != 
				PC_TIMER)
		              __RO_RETURN_RUNTIME( instance, __ROx_BIND_RELREQFAILED )
			else
			{
			   if( TIME > absolute_timeout )
		              __RO_RETURN_RUNTIME( instance, __ROx_BIND_RELREQTIMEOUT );
				
			}
		    }
		    else
		    {
		        if( !presentation_release_state.pr_affirmative )
			    __RO_RETURN_RUNTIME( instance, __ROx_BIND_PRELREQUESTDENIED)
		        else
			    done = 1;
		    }

		    __ROr_ClearSocket(instance->subsystem->specific.isode.association, __ROm_READDIR );
		    __ROr_ClearSocket(instance->subsystem->specific.isode.association, __ROm_WRITEDIR );
		}

	   }
#endif  /* __RO_TASKING */
        }
	else
	{
	   if( !presentation_release_state.pr_affirmative )
	       __RO_RETURN_RUNTIME( instance, __ROx_BIND_PRELREQUESTDENIED);
	}
      PRFREE(&presentation_release_state);
      pe_free(user_data);
   }
   else /* ELSE instance->subsystem->role == RESPONDER *****/
   {
      struct SSAPfinish  	finish;
      struct psapblk		*pb;
      struct PSAPindication	pi;
      struct type_ACS_RLRE__apdu rlre_apdu;
      struct type_ACS_ACSE__apdu *acse_apdu_ptr;
      PE user_data; 
      int user_data_length;
      int smask;
      int result;



		/*
		 * The SI_FINISH was not received.
		 */
	if( !instance->receive_state.done_taken )
	{
		/*
		 * There is still data in the receive buffer.
		 */
	    if( instance->receive_state.buffers != NULL 
			   &&
		(instance->receive_state.buffers->forward != NULL
			   ||
		 instance->receive_state.buffers->data_length != 0 ) )
		__RO_RETURN_RUNTIME( instance, __ROx_BIND_DATAREMAINING );

		/*
		 * Call receive data to get the finish
		 */
	    instance->receive_state.done_available = 1;
	    result = instance->receive_data( instance );
	    if( !(result && instance->except_state.number == __ROx_DONE ) )
		__RO_RETURN_RUNTIME( instance, __ROx_BIND_UNBINDNOTDONE ); 
	
	
	/* Fall through with done */	
	}

		/*
		 * Get the finish state that was save
		 * by ISODEreceive when the finish	
		 * was detected.
		 */
	finish.sf_data = (char *)instance->receive_state.buffers->data_ptr;
	finish.sf_cc = instance->receive_state.buffers->data_length;

				/*
				 * Get psap block from presentation descriptor
				 */
	smask = sigioblock();
	psapPsig( pb, instance->subsystem->specific.isode.association );

 	result = doFINISH( pb, &finish, &pi );
	if( result == NOTOK )
	    __RO_RETURN_RUNTIME(instance, __ROx_BIND_doFINISH );

	(void)sigiomask(smask);

  	result = decode_ACS_ACSE__apdu( pi.pi_finish.pf_info[0],
				1, NULLIP, NULLVP, &acse_apdu_ptr);
	if( result == NOTOK )
	    __RO_RETURN_RUNTIME( instance, __ROx_BIND_ACSEDECODE );
        PFFREE(&pi.pi_finish);
        free_ACS_ACSE__apdu(acse_apdu_ptr);

	memset( &rlre_apdu, 0, sizeof( rlre_apdu ) );
	rlre_apdu.optionals |= opt_ACS_RLRE__apdu_reason;
	rlre_apdu.reason = SC_ACCEPT;
	result = encode_ACS_RLRE__apdu( &user_data, 1, 0, NULLCP, &rlre_apdu );
	if( result == NOTOK )
	    __RO_RETURN_RUNTIME( instance, __ROx_BIND_RLREPDUENCODE );

	user_data->pe_context = instance->ISO_Contexts.acse_pcid;	
	user_data_length = 1;

        if( (PRelResponse( instance->subsystem->specific.isode.association,
  	              SC_ACCEPT, &user_data, user_data_length, &pi ) == NOTOK ))
	    __RO_RETURN_RUNTIME( instance, __ROx_BIND_PRELRESPONSE )
        pe_free(user_data);
   }


   __ROr_free_scatter(instance);
 
   return(SUCCESS);
}


#endif /* __RO_PLATFORM_ISODE */
