static ClRcT clCorDeltaDbContAdd(ClCorDeltaSaveKeyT *deltaDbKey, ClDBRecordT deltaDbData, ClUint32T dataSize)
{
	ClRcT	rc = CL_OK;
	ClCorDeltaSaveKeyT *tempKey = deltaDbKey;
	ClCorDeltaContDataT *tempCont = clHeapCalloc(1, sizeof(ClCorDeltaContDataT));

    CL_ASSERT(tempCont != NULL);

    tempCont->data = deltaDbData;
    tempCont->dataSize = dataSize;

    if( tempKey == NULL || tempCont->data == NULL)
    {
		clLogWrite(CL_LOG_HANDLE_APP, CL_LOG_DEBUG, NULL,
				CL_LOG_MESSAGE_0_MEMORY_ALLOCATION_FAILED);
		CL_DEBUG_PRINT(CL_DEBUG_ERROR,(CL_COR_ERR_STR(CL_COR_ERR_NO_MEM)));
		return CL_COR_SET_RC(CL_COR_ERR_NO_MEM);
    }

    rc = clCntNodeAdd(gCorDeltaSaveKeyTable, (ClCntKeyHandleT) tempKey, (ClCntDataHandleT) tempCont , NULL);
    if(CL_OK != rc)
    {
        if (CL_GET_ERROR_CODE(rc) == CL_ERR_DUPLICATE)
            rc = CL_OK;
        else
            CL_COR_RETURN_ERROR(CL_DEBUG_ERROR, "Could not add node in the Delta Save Key Table", rc);    

        clHeapFree(tempCont);
    }  
	
	return rc;
}
ClRcT clEvtCpmInit()
{
    ClNameT appName;
    ClCpmCallbacksT callbacks;
    ClVersionT version;
    ClIocPortT iocPort;
    ClRcT rc = CL_OK;

    version.releaseCode = 'B';
    version.majorVersion = 0x1;
    version.minorVersion = 0x1;

    callbacks.appHealthCheck = NULL;
    callbacks.appTerminate = clEventTerminate;
    callbacks.appCSISet = NULL;
    callbacks.appCSIRmv = NULL;
    callbacks.appProtectionGroupTrack = NULL;
    callbacks.appProxiedComponentInstantiate = NULL;
    callbacks.appProxiedComponentCleanup = NULL;

    clEoMyEoIocPortGet(&iocPort);

    rc = clCpmClientInitialize(&gClEvtCpmHandle, &callbacks, &version);
    if (CL_OK != rc)
    {
        clLogWrite(CL_LOG_HANDLE_APP, CL_LOG_CRITICAL, NULL,
                   CL_LOG_MESSAGE_2_LIBRARY_INIT_FAILED, "CPM Library", rc);
    }

    rc = clCpmComponentNameGet(gClEvtCpmHandle, &appName);
    rc = clCpmComponentRegister(gClEvtCpmHandle, &appName, NULL);

    return CL_OK;
}
ClRcT clCpmEventPayLoadExtract(ClEventHandleT eventHandle,
                               ClSizeT eventDataSize,
                               ClCpmEventTypeT cpmEventType,
                               void *payLoad)
{
    ClRcT rc = CL_OK;
    ClBufferHandleT payLoadMsg = 0;
    void *eventData = NULL;

    eventData = clHeapAllocate(eventDataSize);
    if (eventData == NULL)
    {
        clLogWrite(CL_LOG_HANDLE_APP, CL_LOG_SEV_DEBUG, CL_CPM_CLIENT_LIB,
                   CL_LOG_MESSAGE_0_MEMORY_ALLOCATION_FAILED);
        CPM_CLIENT_CHECK(CL_LOG_SEV_ERROR, ("Unable to malloc \n"),
                         CL_CPM_RC(CL_ERR_NO_MEMORY));
    }
    rc = clEventDataGet (eventHandle, eventData,  &eventDataSize);
    if (rc != CL_OK)
    {
        clOsalPrintf("Event Data Get failed. rc=[0x%x]\n", rc);
        goto failure;
    }

    rc = clBufferCreate(&payLoadMsg);
    CL_CPM_CHECK_1(CL_LOG_SEV_ERROR, CL_CPM_LOG_1_BUF_CREATE_ERR, rc, rc,
                   CL_LOG_HANDLE_APP);
    rc = clBufferNBytesWrite(payLoadMsg, (ClUint8T *)eventData,
                             eventDataSize);
    CL_CPM_CHECK_1(CL_LOG_SEV_ERROR, CL_CPM_LOG_1_BUF_WRITE_ERR, rc, rc,
                   CL_LOG_HANDLE_APP);

    switch(cpmEventType)
    {
    case CL_CPM_COMP_EVENT:
        rc = VDECL_VER(clXdrUnmarshallClCpmEventPayLoadT, 4, 0, 0)(payLoadMsg, payLoad);
        CL_CPM_CHECK_0(CL_LOG_SEV_ERROR, CL_LOG_MESSAGE_0_INVALID_BUFFER, rc,
                       CL_LOG_HANDLE_APP);
        break;
    case CL_CPM_NODE_EVENT:
        rc = VDECL_VER(clXdrUnmarshallClCpmEventNodePayLoadT, 4, 0, 0)(payLoadMsg, payLoad);
        CL_CPM_CHECK_0(CL_LOG_SEV_ERROR, CL_LOG_MESSAGE_0_INVALID_BUFFER, rc,
                       CL_LOG_HANDLE_APP);
        break;
    default:
        clOsalPrintf("Invalid event type received.\n");
        goto failure;
        break;
    }

failure:
    clBufferDelete(&payLoadMsg);
    clHeapFree(eventData);
    return rc;
}
static void cpmPayload2StandbySC(const ClGmsClusterNotificationBufferT *notificationBuffer,
                                 ClCpmLocalInfoT *pCpmLocalInfo)
{
    ClUint32T rc = CL_OK;

    if(gpClCpm->haState == CL_AMS_HA_STATE_STANDBY)
    {
        clLogWarning(CPM_LOG_AREA_CPM, CPM_LOG_CTX_CPM_AMS,
                     "Payload node already promoted to Deputy. Skipping initialization of controller functions");
        return;
    }

    clLogNotice(CPM_LOG_AREA_CPM, CPM_LOG_CTX_CPM_AMS, 
                "Payload node promoted to deputy. Initializing System controller functions on this node.");

    gpClCpm->pCpmConfig->cpmType = CL_CPM_GLOBAL;
    rc = cpmUpdateTL(CL_AMS_HA_STATE_STANDBY);
    if (rc != CL_OK)
    {
        clLogWrite(CL_LOG_HANDLE_APP, CL_LOG_SEV_DEBUG, NULL,
                   CL_CPM_LOG_1_TL_UPDATE_FAILURE, rc);
    }
    rc = clAmsStart(&gAms,
                    CL_AMS_INSTANTIATE_MODE_STANDBY);
    gpClCpm->haState = CL_AMS_HA_STATE_STANDBY;
    gpClCpm->activeMasterNodeId = notificationBuffer->leader;
    gpClCpm->deputyNodeId = notificationBuffer->deputy;
    if (CL_OK != rc)
    {
        clLogCritical(CPM_LOG_AREA_CPM, CPM_LOG_CTX_CPM_AMS,
                      "Unable to initialize AMS, "
                      "error = [%#x]", rc);

        cpmSelfShutDown();
        return;
    }
    clLogInfo(CPM_LOG_AREA_CPM, CPM_LOG_CTX_CPM_AMS,
              "initialization of AMS is successful. ");
    
    if (gpClCpm->bmTable->currentBootLevel == pCpmLocalInfo->defaultBootLevel)
    {
        cpmInitializeStandby();
    }
    
    clLogNotice(CPM_LOG_AREA_CPM, CPM_LOG_CTX_CPM_AMS,
                "Payload to System Controller conversion done");

    return ;
}
/* happens only once during the booting of the system */
ClRcT clCorMOIdNodeNameMapAdd(ClCorMOIdPtrT pMoId, ClNameT *nodeName)
{
    ClRcT rc;
    /* Add the mapping in both the hash tables */
    /* In this table key is node Name and value is MoId */
    /* allocate MoId first */
    ClCorMOIdPtrT keyMoId = clHeapAllocate(sizeof(ClCorMOIdT));
	ClNameT		  *dataNodeName  = clHeapAllocate (sizeof(ClNameT));
	ClNameT		  *keyNodeName  = clHeapAllocate (sizeof(ClNameT));
    ClCorNodeDataPtrT dataNode = clHeapAllocate(sizeof(ClCorNodeDataT));
    if(dataNode == NULL)
    { 
        CL_DEBUG_PRINT(CL_DEBUG_ERROR,("Failed to allocate Node Data")); 
        return CL_COR_SET_RC(CL_COR_ERR_NO_MEM) ;
    }
    memset(&dataNode->nodeName, 0, sizeof(ClNameT));
    dataNode->pMoId = clHeapAllocate(sizeof(ClCorMOIdT));

    if( keyMoId == NULL || dataNodeName == NULL || dataNode->pMoId == NULL || keyNodeName == NULL)
    {
		clLogWrite(CL_LOG_HANDLE_APP, CL_LOG_DEBUG, NULL,
				CL_LOG_MESSAGE_0_MEMORY_ALLOCATION_FAILED);
		CL_DEBUG_PRINT(CL_DEBUG_ERROR,(CL_COR_ERR_STR(CL_COR_ERR_NO_MEM)));
		return CL_COR_SET_RC(CL_COR_ERR_NO_MEM);
    }

    memcpy(keyMoId, pMoId, sizeof(ClCorMOIdT));
    memcpy(dataNodeName, nodeName, sizeof(ClNameT));
    memcpy(dataNode->pMoId, pMoId, sizeof(ClCorMOIdT));
    memcpy(&dataNode->nodeName, nodeName, sizeof(ClNameT));
    memcpy(keyNodeName, nodeName, sizeof(ClNameT));

    rc = clCntNodeAdd(nodeNameToMoIdTableHandle, (ClCntKeyHandleT) dataNodeName, (ClCntDataHandleT )dataNode , NULL);
    
    if(CL_OK != rc)
        CL_COR_RETURN_ERROR(CL_DEBUG_ERROR, "Could not add node in nodeNameToMoIdHandle", rc);    
    
    /* MOID to Node Name map - In this table key is MOId and value is node name   */
    rc = clCntNodeAdd(moIdToNodeNameTableHandle, (ClCntKeyHandleT) keyMoId, (ClCntDataHandleT)keyNodeName, NULL);

    if(CL_OK != rc)
        CL_COR_RETURN_ERROR(CL_DEBUG_ERROR, "Could not add node in moIdToNodeNameHandle", rc);    
    
    return CL_OK;
}
ClRcT
clDebugPromptSet(const ClCharT  *pCompPrompt)
{
    ClEoExecutionObjT  *pEoObj    = NULL; 
    ClDebugObjT        *pDebugObj = NULL;
    ClRcT              rc         = CL_OK;

    if( NULL == pCompPrompt )
    {
        CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("Passed Prompt is NULL"));
        return CL_DEBUG_RC(CL_ERR_NULL_POINTER);
    }
    rc = clEoMyEoObjectGet(&pEoObj);
    if (CL_OK != rc)
    {
        CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("clEoMyEoObjectGet(): rc[0x %x]",
                    rc));
        return rc;
    }
    rc = clEoPrivateDataGet( pEoObj,
                             CL_EO_DEBUG_OBJECT_COOKIE_ID,
                             (void**) &pDebugObj);
    if (CL_OK != rc)
    {
        CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("clEoPrivateDataGet(): rc[0x %x]",
                    rc));
        return rc;
    }

    if (strlen(pCompPrompt) < CL_DEBUG_COMP_PROMPT_LEN)
    {
        strcpy(pDebugObj->compPrompt, pCompPrompt);
    }
    else
    {
        clLogWrite(CL_LOG_HANDLE_APP,CL_LOG_WARNING,CL_DEBUG_LIB_CLIENT,
                   CL_LOG_MESSAGE_1_INVALID_PARAMETER,"Prompt is Invalid");
        return CL_DEBUG_RC(CL_ERR_INVALID_PARAMETER);
    }

    return CL_OK;
}
ClRcT initializeAmf()
{
   
    SaNameT             appName;      
    SaAmfCallbacksT     callbacks;
    SaVersionT          version;
    ClIocPortT          iocPort;
    SaAisErrorT         rc = SA_AIS_OK;

    
    version.releaseCode  = 'B';
    version.majorVersion = 0x01;
    version.minorVersion = 0x01;
    
    callbacks.saAmfHealthcheckCallback          = NULL; /* rarely necessary because SAFplus monitors the process */
    callbacks.saAmfComponentTerminateCallback   = clEventTerminate;
    callbacks.saAmfCSISetCallback               = NULL;
    callbacks.saAmfCSIRemoveCallback            = NULL;
    callbacks.saAmfProtectionGroupTrackCallback = NULL;
    callbacks.saAmfProxiedComponentInstantiateCallback = NULL;
    callbacks.saAmfProxiedComponentCleanupCallback = NULL;

    clEoMyEoIocPortGet(&iocPort);
   
    rc = saAmfInitialize(&gClEvtAmfHandle, &callbacks, &version);
    if(rc != SA_AIS_OK)
    {
        clLogWrite(CL_LOG_HANDLE_APP, CL_LOG_CRITICAL, NULL,
                   CL_LOG_MESSAGE_2_LIBRARY_INIT_FAILED, "CPM Library", rc);
        return clSafToClovisError(rc);
    }

    rc = saAmfComponentNameGet(gClEvtAmfHandle, &appName);
    rc = saAmfComponentRegister(gClEvtAmfHandle, &appName, NULL);

    return CL_OK;
    
}
ClRcT cpmPrintDBXML(FILE *fp)
{
    ClRcT rc = CL_OK;
    ClCntNodeHandleT cpmNode = 0;
    ClUint32T cpmLCount = 0;
    ClCpmLT *cpmL = NULL;

    fprintf(fp,"<cpm>\n");

    /*
     * Walk through the cpm table to find and display SCs 
     */
    clOsalMutexLock(gpClCpm->cpmTableMutex);
    cpmLCount = gpClCpm->noOfCpm;
    if (gpClCpm->pCpmConfig->cpmType == CL_CPM_GLOBAL && cpmLCount != 0)
    {
        rc = clCntFirstNodeGet(gpClCpm->cpmTable, &cpmNode);
        if(rc != CL_OK)
        {
            clLogError(CPM_LOG_AREA_DB,CPM_LOG_CTX_DB_XML,CL_CPM_LOG_2_CNT_FIRST_NODE_GET_ERR, "CPM-L", rc);
            clLogWrite((CL_LOG_HANDLE_APP), (CL_LOG_SEV_DEBUG), NULL, CL_CPM_LOG_2_CNT_FIRST_NODE_GET_ERR, ("CPM-L"), (rc));
            goto out_unlock;
        }

        while (cpmLCount)
        {
            rc = clCntNodeUserDataGet(gpClCpm->cpmTable, cpmNode,
                                    (ClCntDataHandleT *) &cpmL);

            if(rc != CL_OK)
            {
                clLogError(CPM_LOG_AREA_DB,CPM_LOG_CTX_DB_XML,CL_CPM_LOG_1_CNT_NODE_USR_DATA_GET_ERR, rc);
                clLogWrite((CL_LOG_HANDLE_APP), (CL_LOG_SEV_DEBUG), NULL, CL_CPM_LOG_1_CNT_NODE_USR_DATA_GET_ERR, rc);
                goto out_unlock;
            }

            if (cpmL->pCpmLocalInfo)
            {
                /*
                 * If the node is a SC, display its data 
                 */
                if(!strcmp((const ClCharT *)cpmL->nodeType.value, (const ClCharT *)gpClCpm->pCpmLocalInfo->nodeType.value)
                    || (ClUint32T) cpmL->pCpmLocalInfo->nodeId == gpClCpm->activeMasterNodeId
                    || (ClUint32T) cpmL->pCpmLocalInfo->nodeId == gpClCpm->deputyNodeId)
                {
                    fprintf(fp,"<node value=\"%s\">\n",cpmL->pCpmLocalInfo->nodeName);
                    fprintf(fp,"<id value=\"%d\"/>\n",cpmL->pCpmLocalInfo->nodeId);
                    fprintf(fp,"<ha_state value=\"%s\"/>\n",(ClUint32T) cpmL->pCpmLocalInfo->nodeId == gpClCpm->activeMasterNodeId ? "active" : "standby");
                    fprintf(fp,"</node>\n");
                }
            }

            cpmLCount--;

            if (cpmLCount)
            {
                rc = clCntNextNodeGet(gpClCpm->cpmTable, cpmNode, &cpmNode);
                if(rc != CL_OK)
                {
                    clLogError(CPM_LOG_AREA_DB,CPM_LOG_CTX_DB_XML,CL_CPM_LOG_2_CNT_NEXT_NODE_GET_ERR, "CPM-L", rc);
                    clLogWrite((CL_LOG_HANDLE_APP), (CL_LOG_SEV_DEBUG), NULL, CL_CPM_LOG_2_CNT_NEXT_NODE_GET_ERR, ("CPM-L"), (rc));
                    goto out_unlock;
                }
            }
        }
    }

    rc = CL_OK;
    out_unlock:
    clOsalMutexUnlock(gpClCpm->cpmTableMutex);

    fprintf(fp,"</cpm>\n");
    return rc;
}
/*
 * This function will do following steps 
 * 1. Create DB for ECH/G 
 * 2. Create DB for ECH/L 
 * 3. Create mutex to protect ECH/G DB 
 * 4. Create mutex to protect ECH/L DB 
 * 5. Register with CPM for component failure notification. 
 * 6. Intialize the global variable to indicate EM is done. 
 */
ClRcT clEvtInitialize(ClInt32T argc, ClCharT *argv[])
{

    ClRcT rc = CL_OK;

    rc = initializeAmf();
    if (rc != CL_OK)
    {
        CL_DEBUG_PRINT(CL_DEBUG_CRITICAL,
                       ("Event: Amf Initialization failed [0x%X]\n\r", rc));
        CL_FUNC_EXIT();
        return rc;
    }

    CL_FUNC_ENTER();

    rc = clEvtChannelDBInit();

    rc = clEoMyEoObjectGet(&gEvtHead.evtEOId);

    rc = clEoClientInstallTables(gEvtHead.evtEOId, CL_EO_SERVER_SYM_MOD(gAspFuncTable, EVT));
    if (rc != CL_OK)
    {
        CL_DEBUG_PRINT(CL_DEBUG_CRITICAL,
                       ("Event: Installing Native table failed [0x%X]\n\r",
                        rc));
        clLogWrite(CL_LOG_HANDLE_APP, CL_LOG_CRITICAL, NULL,
                   CL_LOG_MESSAGE_1_FUNC_TABLE_INSTALL_FAILED, rc);
        clCntDelete(gEvtMasterECHHandle);
        clEvtChannelDBClean();
        CL_FUNC_EXIT();
        return rc;
    }

    rc = clEventLibTableInit(); 
    if(rc != CL_OK)
    {
        CL_DEBUG_PRINT(CL_DEBUG_CRITICAL,
                       ("Event: Installing Native Server to Server table failed [0x%X]\n\r",
                        rc));
        clLogWrite(CL_LOG_HANDLE_APP, CL_LOG_CRITICAL, NULL,
                   CL_LOG_MESSAGE_1_FUNC_TABLE_INSTALL_FAILED, rc);
        clCntDelete(gEvtMasterECHHandle);
        clEvtChannelDBClean();
        CL_FUNC_EXIT();
        return rc;
    }


    rc = clEventDebugRegister(gEvtHead.evtEOId);
    if (rc != CL_OK)
    {
        CL_DEBUG_PRINT(CL_DEBUG_CRITICAL,
                       ("Event: Debug Register failed [0x%X]\n\r", rc));
        clLogWrite(CL_LOG_HANDLE_APP, CL_LOG_CRITICAL, NULL,
                   CL_LOG_MESSAGE_1_DBG_REGISTER_FAILED, rc);
        CL_FUNC_EXIT();
        return rc;
    }

    /*
     ** Initialize the Handle Database.
     */
    rc = clEvtHandleDatabaseInit();
    if (rc != CL_OK)
    {
        CL_DEBUG_PRINT(CL_DEBUG_CRITICAL,
                       ("Event: Handle Database Init failed [0x%X]\n\r", rc));
        CL_FUNC_EXIT();
        return rc;
    }

#ifdef CKPT_ENABLED
    /*
     ** Initialize the Check Pointing Library.
     */
    rc = clEvtCkptInit();
    if (rc != CL_OK)
    {
        CL_DEBUG_PRINT(CL_DEBUG_CRITICAL,
                       ("Event: CKPT Init failed [0x%X]\n\r", rc));
        clLogWrite(CL_LOG_HANDLE_APP, CL_LOG_CRITICAL, NULL,
                   CL_LOG_MESSAGE_2_LIBRARY_INIT_FAILED, "Checkpoint Library",
                   rc);
        CL_FUNC_EXIT();
        return rc;
    }
#endif


    gEvtInitDone = CL_EVT_TRUE;

    /*
     * CPM should be notified that Event Service is ready only after the
     * the initialization is complete. This _MUST_ be the last step.
     */
    

    CL_FUNC_EXIT();

    return CL_OK;
}
ClRcT  VDECL(_corMOTreeClassOpRmd) (ClEoDataT cData, ClBufferHandleT  inMsgHandle,
                                  ClBufferHandleT  outMsgHandle)
{
    ClRcT rc = CL_OK;
    corClassDetails_t *pClassInfo = NULL;
    CORMOClass_h moClassHandle;
    CORMSOClass_h msoClassHandle;

    CL_FUNC_ENTER();

    if(gCorInitStage == CL_COR_INIT_INCOMPLETE)
    {
        clLogError("MOT", "EOF", "The COR server Initialization is in progress....");
        return CL_COR_SET_RC(CL_COR_ERR_TRY_AGAIN);
    }
    
    pClassInfo = clHeapAllocate(sizeof(corClassDetails_t));
    if(pClassInfo == NULL) 
    {
        CL_DEBUG_PRINT(CL_DEBUG_ERROR, ( "NULL argument"));
        CL_FUNC_EXIT();
        return(CL_COR_SET_RC(CL_COR_ERR_NULL_PTR));
    }

	if((rc = VDECL_VER(clXdrUnmarshallcorClassDetails_t, 4, 0, 0)(inMsgHandle, (void *)pClassInfo)) != CL_OK)
	{
		clHeapFree(pClassInfo);
		CL_DEBUG_PRINT(CL_DEBUG_ERROR,("Failed to Unmarshall corClassDetails_t "));
		return rc;
	}
    /* if((rc = clBufferFlatten(inMsgHandle, (ClUint8T **)&pClassInfo))!= CL_OK)
    {
                CL_DEBUG_PRINT(CL_DEBUG_ERROR, ( "Failed to flatten the Message"));
                CL_FUNC_EXIT();
	        return rc;
    }*/	
    /* if(pClassInfo->version > CL_COR_VERSION_NO)
    {
		clHeapFree(pClassInfo);
        CL_DEBUG_PRINT(CL_DEBUG_ERROR, ( "Version mismatch"));
        CL_FUNC_EXIT();
        return CL_ERR_VERSION_MISMATCH;
    }*/

	clCorClientToServerVersionValidate(pClassInfo->version, rc);
    if(rc != CL_OK)
	{
		clHeapFree(pClassInfo);	
		return CL_COR_SET_RC(CL_COR_ERR_VERSION_UNSUPPORTED); 
	}
  
    switch(pClassInfo->operation)
    {
        case COR_CLASS_OP_CREATE:
            if(pClassInfo->classType == MO_CLASS)
            {
                rc = _corMOClassCreate(&(pClassInfo->corPath), pClassInfo->maxInstances, &moClassHandle);
                if(rc != CL_OK)
                {
                    clHeapFree(pClassInfo);
                    clLogWrite(CL_LOG_HANDLE_APP, CL_LOG_ERROR, NULL,
						CL_LOG_MESSAGE_1_MOCLASS_CREATE, rc);
                    CL_DEBUG_PRINT(CL_DEBUG_ERROR, ( "_corMOClassCreate failure"));
                    CL_FUNC_EXIT();
                    return rc;
                }
            }
            else
            {
                rc = corMOClassHandleGet(&(pClassInfo->corPath), &moClassHandle);
                if(rc != CL_OK)
                {
                    CL_DEBUG_PRINT(CL_DEBUG_ERROR, ( "corMOClassHandleGet failure"));
                }
                else
                {
                	rc = _corMSOClassCreate(moClassHandle, pClassInfo->svcId,
                       	                pClassInfo->objClass, &msoClassHandle);
                    if(rc != CL_OK)
               			CL_DEBUG_PRINT(CL_DEBUG_ERROR, ( "_corMSOClassCreate failure"));
                }

               	if(rc != CL_OK)
               	{
                    clHeapFree(pClassInfo);
                    clLogWrite(CL_LOG_HANDLE_APP, CL_LOG_ERROR, NULL,
					CL_LOG_MESSAGE_1_MSOCLASS_CREATE, rc);
               		CL_FUNC_EXIT();
               		return rc;
                }
            }
            break;
        case COR_CLASS_OP_DELETE:
            if(pClassInfo->classType == MO_CLASS)
            {
                rc = _corMOClassDelete(&(pClassInfo->corPath));
                if(rc != CL_OK)
                {
                    clHeapFree(pClassInfo);
                    clLogWrite(CL_LOG_HANDLE_APP, CL_LOG_ERROR, NULL,
					CL_LOG_MESSAGE_1_MOCLASS_DELETE, rc);
                    CL_DEBUG_PRINT(CL_DEBUG_ERROR, ( "_corMOClassDelete failure"));
                    CL_FUNC_EXIT();
                    return rc;
                }
            }
            else
            {
                rc = corMOClassHandleGet(&(pClassInfo->corPath), &moClassHandle);
                if(rc != CL_OK)
                    CL_DEBUG_PRINT(CL_DEBUG_ERROR, ( "corMOClassHandleGet failure"));
                else
                {
                    rc = _corMSOClassDelete(moClassHandle, pClassInfo->svcId);
                    if(rc != CL_OK)
                        CL_DEBUG_PRINT(CL_DEBUG_ERROR, ( "_corMSOClassDelete failure"));
                }

                if(rc != CL_OK)
               	{
                    clHeapFree(pClassInfo);
                    clLogWrite(CL_LOG_HANDLE_APP, CL_LOG_ERROR, NULL,
						CL_LOG_MESSAGE_1_MSOCLASS_DELETE, rc);
                    CL_FUNC_EXIT();
                    return rc;
                }
            }
            break;
        case COR_CLASS_OP_EXISTANCE:
            if(pClassInfo->classType == MO_CLASS)
            {
                rc = corMOClassHandleGet(&(pClassInfo->corPath), &moClassHandle);
                if(rc != CL_OK)
                {
					clHeapFree(pClassInfo);
                    CL_DEBUG_PRINT(CL_DEBUG_TRACE, ( "corMOClassHandleGet failure"));
                    CL_FUNC_EXIT();
                    return rc;
                }
            }
            else
            {
                rc = corMOClassHandleGet(&(pClassInfo->corPath), &moClassHandle);
                if(rc != CL_OK)
                {
					clHeapFree(pClassInfo);
                    CL_DEBUG_PRINT(CL_DEBUG_TRACE, ( "corMOClassHandleGet failure"));
                    CL_FUNC_EXIT();
                    return rc;
                }
                rc = corMSOClassHandleGet(moClassHandle, pClassInfo->svcId, &msoClassHandle);
                if(rc != CL_OK)
                {
					clHeapFree(pClassInfo);
                    CL_DEBUG_PRINT(CL_DEBUG_TRACE, ( "corMSOClassHandleGet failure"));
                    CL_FUNC_EXIT();
                    return rc;
                }
            }
            break;
        case COR_CLASS_OP_CLASSID_GET:
            rc = _corMOPathToClassIdGet(&(pClassInfo->corPath), pClassInfo->svcId, &(pClassInfo->objClass));
            if(rc != CL_OK)
            {
				clHeapFree(pClassInfo);
                CL_DEBUG_PRINT(CL_DEBUG_TRACE, ( "corMSOClassHandleGet failure"));
                CL_FUNC_EXIT();
                return rc;
            }
            /*Write to the message.*/
            /* clBufferNBytesWrite (outMsgHandle, (ClUint8T *)pClassInfo, sizeof(corClassDetails_t)); */
			VDECL_VER(clXdrMarshallcorClassDetails_t, 4, 0, 0)(pClassInfo, outMsgHandle, 0);
            break;
        case COR_CLASS_OP_FIRSTCHILD_GET:
            rc = _clCorMoClassPathFirstChildGet(&(pClassInfo->corPath));
            if(rc != CL_OK)
            {
				clHeapFree(pClassInfo);
                CL_DEBUG_PRINT(CL_DEBUG_TRACE, ( "_clCorMoPathFirstChildGet failure"));
                CL_FUNC_EXIT();
                return rc;
            }
            /*Write to the message.*/
            /* clBufferNBytesWrite (outMsgHandle, (ClUint8T *)pClassInfo, sizeof(corClassDetails_t)); */
			VDECL_VER(clXdrMarshallcorClassDetails_t, 4, 0, 0)(pClassInfo, outMsgHandle, 0);
            break;
        case COR_CLASS_OP_NEXTSIBLING_GET:
            rc = _clCorMoClassPathNextSiblingGet(&(pClassInfo->corPath));
            if(rc != CL_OK)
            {
				clHeapFree(pClassInfo);
                CL_DEBUG_PRINT(CL_DEBUG_TRACE, ( "_clCorMoPathNextSiblingGet failure"));
                CL_FUNC_EXIT();
                return rc;
            }
            /*Write to the message.*/
            /* clBufferNBytesWrite (outMsgHandle, (ClUint8T *)pClassInfo, sizeof(corClassDetails_t)); */
			VDECL_VER(clXdrMarshallcorClassDetails_t, 4, 0, 0)(pClassInfo, outMsgHandle, 0);
            break;
        default:
			CL_DEBUG_PRINT(CL_DEBUG_ERROR,("MOClass Request Type %d", pClassInfo->operation));
            break;
    }

    if (pClassInfo->operation == COR_CLASS_OP_CREATE ||
            pClassInfo->operation == COR_CLASS_OP_DELETE)
    {
        if (gCorSlaveSyncUpDone == CL_TRUE)
        {
            ClRcT retCode = CL_OK;

            retCode = clCorSyncDataWithSlave(COR_EO_MOTREE_OP, inMsgHandle);
            if (retCode != CL_OK)
            {
                clLogError("SYNC", "", "Failed to sync data with slave COR. rc [0x%x]", rc);
                /* Ignore the error code. */
            }
        }
    }

    CL_FUNC_EXIT();
	clHeapFree(pClassInfo);
    return rc;
}
/** 
 *  Initialize COR notification module.
 *
 *  This routine initializes COR notification module. It creates
 * the COR event channel in EM. This routine is called during
 * COR initialization from corInit. This is not an external API.
 *
 *  @param  N/A
 *
 *  @returns CL_OK  on success<br>
 *       value returned by #emEventCreate on failure.
 */
ClRcT 
corEventInit(void)
{
	ClRcT rc;
	ClNameT evtChannelName;
	ClVersionT ver = CL_EVENT_VERSION;
    ClUint32T                 compDeathPattern   = htonl(CL_CPM_COMP_DEATH_PATTERN);
    ClUint32T                 compDeparturePattern   = htonl(CL_CPM_COMP_DEPART_PATTERN);

    ClUint32T                 nodeDeathPattern = htonl(CL_CPM_NODE_DEATH_PATTERN);
    ClUint32T                 nodeDeparturePattern = htonl(CL_CPM_NODE_DEPART_PATTERN);

    ClEventFilterT            compDeathFilter[]  = {{CL_EVENT_EXACT_FILTER, 
                                                {0, (ClSizeT)sizeof(compDeathPattern), (ClUint8T*)&compDeathPattern}}
    };
    ClEventFilterArrayT       compDeathFilterArray = {sizeof(compDeathFilter)/sizeof(compDeathFilter[0]), 
                                                     compDeathFilter
    };

    ClEventFilterT            compDepartureFilter[]  = {{CL_EVENT_EXACT_FILTER, 
                                                {0, (ClSizeT)sizeof(compDeparturePattern), (ClUint8T*)&compDeparturePattern}}
    };
    ClEventFilterArrayT       compDepartureFilterArray = {sizeof(compDepartureFilter)/sizeof(compDepartureFilter[0]), 
                                                     compDepartureFilter
    };

    ClEventFilterT            nodeDeathFilter[]         = { {CL_EVENT_EXACT_FILTER,
                                                                {0, (ClSizeT)sizeof(nodeDeathPattern),
                                                                (ClUint8T*)&nodeDeathPattern}}
    };
    ClEventFilterArrayT       nodeDeathFilterArray = {sizeof(nodeDeathFilter)/sizeof(nodeDeathFilter[0]),
                                                          nodeDeathFilter 
    };

    ClEventFilterT            nodeDepartureFilter[]         = { {CL_EVENT_EXACT_FILTER,
                                                                {0, (ClSizeT)sizeof(nodeDeparturePattern),
                                                                (ClUint8T*)&nodeDeparturePattern}}
    };
    ClEventFilterArrayT       nodeDepartureFilterArray = {sizeof(nodeDepartureFilter)/sizeof(nodeDepartureFilter[0]),
                                                          nodeDepartureFilter 
    };

	CL_FUNC_ENTER();
	
	/* First call the function to initialize COR events */
	rc = clEventInitialize(&corEventHandle,&corEvtCallbacks, &ver);

	if(CL_OK != rc)
	{
               clLogWrite(CL_LOG_HANDLE_APP, CL_LOG_ALERT, NULL, 
					CL_LOG_MESSAGE_2_INIT, "Event Client", rc);
		CL_DEBUG_PRINT (CL_DEBUG_ERROR, ("Event Client init failed rc => [0x%x]\n", rc));
		return rc;
	}


	/**** Open Publish Channel for COR */
	evtChannelName.length = strlen(clCorEventName);
	memcpy(evtChannelName.value, clCorEventName, evtChannelName.length+1);
		
	rc = clEventChannelOpen(corEventHandle, &evtChannelName, 
			CL_EVENT_GLOBAL_CHANNEL | CL_EVENT_CHANNEL_PUBLISHER, 
			COR_EVT_TIMEOUT, 
			&corEventChannelHandle);
	
	if(CL_OK != rc)
	{
               clLogWrite(CL_LOG_HANDLE_APP, CL_LOG_ALERT, NULL,
					CL_LOG_MESSAGE_1_EVENT_PUBLISH_CHANNEL_OPEN, rc); 
		CL_DEBUG_PRINT (CL_DEBUG_ERROR, ("\n Event Publish Channel Open failed for COR rc => [0x%x]\n", rc));
		return rc;
	}

	/**
     * Open component event channel of CPM 
     */
	evtChannelName.length = strlen(CL_CPM_EVENT_CHANNEL_NAME);
        strcpy(evtChannelName.value, CL_CPM_EVENT_CHANNEL_NAME);
		
	rc = clEventChannelOpen(corEventHandle, &evtChannelName, 
			CL_EVENT_GLOBAL_CHANNEL | CL_EVENT_CHANNEL_SUBSCRIBER, 
			(ClTimeT)-1, 
			&cpmEventChannelHandle);
	if(CL_OK != rc)
	{
                clLogWrite(CL_LOG_HANDLE_APP, CL_LOG_ALERT, NULL, 
						CL_LOG_MESSAGE_1_CHANNEL_OPEN_COMP_TERMINATION, rc);
		CL_DEBUG_PRINT (CL_DEBUG_ERROR, ("\n Event Subscribe Channel Open failed for CPM rc => [0x%x]\n", rc));
		return rc;
	}

    /*
     * Subscribe for component death event.
     */
    rc = clEventSubscribe(cpmEventChannelHandle, &compDeathFilterArray, CL_COR_COMP_DEATH_SUBSCRIPTION_ID, NULL);
    if(CL_OK != rc)
    {
        clLogError("NOTIFY", "SUBSCRIBE", "Failed to subscribe for component death event. rc [0x%x]", rc);
        return rc;
    }

	/*
     * Subscribe for component departure event. 
     */
    rc = clEventSubscribe(cpmEventChannelHandle, &compDepartureFilterArray, CL_COR_COMP_DEPARTURE_SUBSCRIPTION_ID, NULL);
    if(CL_OK != rc)
    {
        clLogError("NOTIFY", "SUBSCRIBE", "Failed to subscribe for component departure event. rc [0x%x]", rc);
        return rc;
    }
	
    /**
     * Open node event channel of CPM.
     */
	evtChannelName.length = strlen(CL_CPM_NODE_EVENT_CHANNEL_NAME);
    strcpy(evtChannelName.value, CL_CPM_NODE_EVENT_CHANNEL_NAME);
		
	rc = clEventChannelOpen(corEventHandle, &evtChannelName, 
			CL_EVENT_GLOBAL_CHANNEL | CL_EVENT_CHANNEL_SUBSCRIBER, 
			(ClTimeT)-1, 
			&cpmEventNodeChannelHandle);
	if(CL_OK != rc)
	{
             clLogWrite(CL_LOG_HANDLE_APP, CL_LOG_ALERT, NULL, 
					CL_LOG_MESSAGE_1_CHANNEL_OPEN_NODE_ARRIVAL, rc);
             CL_DEBUG_PRINT (CL_DEBUG_ERROR, ("\n Event Subscribe Channel Open failed for CPM rc => [0x%x]\n", rc));
	     return rc;
	}

    /*
     * Subscribe for node death event.
     */
    rc = clEventSubscribe(cpmEventNodeChannelHandle, &nodeDeathFilterArray, 
                          CL_COR_NODE_DEATH_SUBSCRIPTION_ID, NULL);
    if(CL_OK != rc)
    {
        clLogError("NOTIFY", "SUBSCRIBE", "Failed to subscribe for node death event. rc [0x%x]", rc);
        return rc;
    }

    /*
     * Subscribe for node departure event.
     */
    rc = clEventSubscribe(cpmEventNodeChannelHandle, &nodeDepartureFilterArray, 
                          CL_COR_NODE_DEPARTURE_SUBSCRIPTION_ID, NULL);
    if(CL_OK != rc)
    {
        clLogError("NOTIFY", "SUBSCRIBE", "Failed to subscribe for node departure event. rc [0x%x]", rc);
        return rc;
    }

    CL_FUNC_EXIT();
    return (rc);
}
ClRcT VDECL(_corObjectWalkOp) (ClEoDataT cData, ClBufferHandleT  inMsgHandle,
                                  ClBufferHandleT  outMsgHandle)
{
    ClRcT rc = CL_OK;
    corObjFlagNWalkInfoT* pData = NULL;
    CL_FUNC_ENTER();

    if(gCorInitStage == CL_COR_INIT_INCOMPLETE)
    {
        clLogError("OBW", "EOF", "The COR server Initialization is in progress....");
        return CL_COR_SET_RC(CL_COR_ERR_TRY_AGAIN);
    }

    pData = clHeapAllocate(sizeof(corObjFlagNWalkInfoT));
    if(!pData)
    {
          clLogWrite(CL_LOG_HANDLE_APP, CL_LOG_DEBUG, gCorClientLibName,
                    CL_LOG_MESSAGE_0_MEMORY_ALLOCATION_FAILED);
           CL_DEBUG_PRINT(CL_DEBUG_ERROR,(CL_COR_ERR_STR(CL_COR_ERR_NO_MEM)));
           return (CL_COR_SET_RC(CL_COR_ERR_NO_MEM));
    }

    if((rc = VDECL_VER(clXdrUnmarshallcorObjFlagNWalkInfoT, 4, 0, 0)(inMsgHandle, (void *)pData)) != CL_OK)
    {
        CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("Failed to Unmarshall corObjFlagNWalkInfoT"));
            clHeapFree(pData);
        return rc;
    }

	clCorClientToServerVersionValidate(pData->version, rc);
    if(rc != CL_OK)
	{
		clHeapFree(pData);	
		return CL_COR_SET_RC(CL_COR_ERR_VERSION_UNSUPPORTED); 
	}

    switch(pData->operation)
    {
        case COR_OBJ_WALK_DATA_GET:
            clOsalMutexLock(gCorMutexes.gCorServerMutex);

#if 0            
            objHdlCount = 0;
            rc = _corObjectCountGet(&iCount);
            pObjHdlList = (char *) clHeapAllocate(iCount*sizeof(ClCorObjectHandleT));
	   	    if(pObjHdlList == NULL)
	        {
       			 clHeapFree(pData);
            	 clOsalMutexUnlock(gCorMutexes.gCorServerMutex); 
			  	 clLogWrite(CL_LOG_HANDLE_APP, CL_LOG_DEBUG, NULL,
					CL_LOG_MESSAGE_0_MEMORY_ALLOCATION_FAILED);
 				 CL_DEBUG_PRINT(CL_DEBUG_ERROR,(CL_COR_ERR_STR(CL_COR_ERR_NO_MEM)));
				 return CL_COR_SET_RC(CL_COR_ERR_NO_MEM);
	    	}

            clLogTrace("OBW", "EFN", "Going for the object walk now");
#endif

            rc = _clCorObjectWalk(&pData->moId, &pData->moIdWithWC, _corObjHdlListGet, pData->flags, outMsgHandle);
            if (CL_OK != rc)
            {
                clLogError("OBW", "EFN", 
                        "Failed to do the object walk on server. rc[0x%x]", rc);
            }
#if 0
            else
            {
	            rc = clBufferNBytesWrite(outMsgHandle, (ClUint8T *)pObjHdlList,
            	                (ClUint32T)objHdlCount * sizeof(ClCorObjectHandleT));
                if (CL_OK != rc)
                    clLogError("OBW", "EFN", 
                            "Failed to write the object walk information into the out buffer. rc[0x%x]", rc);
            }

            clLogTrace("OBW", "EFN", "Done with the object walk");

            clHeapFree(pObjHdlList);
#endif
            clOsalMutexUnlock(gCorMutexes.gCorServerMutex); 
        break;
        case COR_OBJ_SUBTREE_DELETE:
           clOsalMutexLock(gCorMutexes.gCorServerMutex);
           rc = _clCorSubTreeDelete(pData->moId);
           clOsalMutexUnlock(gCorMutexes.gCorServerMutex); 
        break;
        default:
             CL_DEBUG_PRINT(CL_DEBUG_ERROR, ( "INVALID OPERATION, rc = %x", rc) );
             rc = CL_COR_SET_RC(CL_COR_ERR_INVALID_PARAM);
        break;
    }
   
    CL_FUNC_EXIT();
    clHeapFree(pData);
    return rc;
}
/* 
 * this api is used to for querying the fault history
 * for a particular set of attributes from the cli.
 */
ClRcT
clFaultCliDebugHistoryShow( ClUint32T argc, 
                            ClCharT **argv, 
                            ClCharT** ret)
{
    ClRcT               rc = CL_OK;
    SaNameT             moIdName = {0};
    ClUint8T            catIndex, sevIndex;
    ClUint8T    		recordFound = 0;	
    ClCorMOIdT          moid;
    ClFaultRecordT*     fRecord;
    ClFaultRecordPtr 	historyRec;
    ClCorObjectHandleT  hMSOObj;

    if ( argc != 6 )
    {
        clFaultCliStrPrint(ret, "\nUsage : queryFaulthistory <Moid>"
                " <Category#> <SpecificProblem#> <Severity#> <Cause#>\n"
                "\tMoid [STRING]    : This is the absolute path of the MOID"
                "i.e \\Class_Chassis:0\\Class_GigeBlade:1 \n"
                "\tCategory [DEC]   : Category of the fault\n"
                "\tValid values are : 1 for COMMUNICATIONS, 2 for QUALITY OF SERVICE,\n\t\t\t   3 for PROCESSING ERROR, 4 for EQUIPMENT,\n\t\t\t   5 for ENVIRONMENTAL\n\n"
                "\tSpecProblem[DEC] : Specific problem of the fault\n"
                "\tSeverity [DEC]   : Severity of the fault\n"
                "\tValid values are : 1 for CRITICAL, 2 for MAJOR,\n\t\t\t   3 for MINOR, 4 for WARNING,\n\t\t\t   5 for INTERMEDIATE, 6 for CLEAR\n\n"
                "\tCause [DEC]      : Cause of the fault\n"
                "\tValid values are : 1 to 57. Refer ClAlarmProbableCauseT for more description\n");
        return CL_OK;
    }
    //rc = clFaultXlateMOPath (argv[1], &moid );
    strcpy(moIdName.value, argv[1]);
    moIdName.length = strlen(argv[1]);
    rc = clCorMoIdNameToMoIdGet(&moIdName, &moid);
    if ( CL_OK == rc)
    {
        fRecord =(ClFaultRecordT*)clHeapAllocate(sizeof(ClFaultRecordT));

        historyRec = (ClFaultRecordPtr)clHeapAllocate(sizeof(ClFaultRecordT));	

        if(fRecord == NULL || historyRec == NULL)
        {
            clLogWrite(CL_LOG_HANDLE_SYS, CL_LOG_SEV_CRITICAL, CL_FAULT_SERVER_LIB,
                    CL_LOG_MESSAGE_0_MEMORY_ALLOCATION_FAILED);
            return CL_FAULT_RC(CL_ERR_NO_MEMORY);
        }
                            
        rc = clCorObjectHandleGet(&moid, &hMSOObj);
        if (CL_OK != rc)
        {
            clFaultCliStrPrint(ret, " Invalid MoId passed..... \n");
            clHeapFree(fRecord);
            clHeapFree(historyRec);
            return rc;
        }
        (fRecord->event).category = atoi(argv[2]);
        (fRecord->event).specificProblem = atoi(argv[3]);
        (fRecord->event).severity = atoi(argv[4]);
        (fRecord->event).cause = atoi(argv[5]);
        if((fRecord->event).cause < CL_ALARM_PROB_CAUSE_LOSS_OF_SIGNAL 
                        ||
           (fRecord->event).cause > CL_ALARM_PROB_CAUSE_ENCLOSURE_DOOR_OPEN)
        {
            clFaultCliStrPrint(ret, 
                    "Invalid probable cause [%s] supplied. Please see usage for the valid range of values\n");
            return CL_FAULT_ERR_INVLD_VAL;
        }
        (fRecord->event).moId = moid;	
                            
        (fRecord->event).category=
            clFaultCategory2InternalTranslate((fRecord->event).category);
        (fRecord->event).severity=
            clFaultSeverity2InternalTranslate((fRecord->event.severity));

        if ( (rc = clFaultCategory2IndexTranslate(
                        (fRecord->event).category, &catIndex)) != CL_OK )
        {
            clFaultCliStrPrint(ret, 
                    "\nFM REPAIR, Invalid CATEGORY. CANNOT PROCESS QUERY\n");
            clHeapFree(fRecord);
            clHeapFree(historyRec);
            return CL_OK;
        }
        if( (rc = clFaultSeverity2IndexTranslate(
                        (fRecord->event).severity, &sevIndex)) != CL_OK )
        {
            clFaultCliStrPrint(ret, 
                    "\nFM REPAIR, Invalid SEVERITY. CANNOT PROCESS QUERY\n");
            clHeapFree(fRecord);
            clHeapFree(historyRec);
            return rc;
        }

        rc = clFaultHistoryDataLock();
        if (rc != CL_OK)
        {
            clFaultCliStrPrint(ret, 
                    " REPAIR: Not able to get history data lock rc [0x%x]\n", rc);
            clHeapFree(fRecord);
            clHeapFree(historyRec);
            return rc;
        }
        rc = clFaultProcessFaultRecordQuery(&(fRecord->event.moId),
                                               (fRecord->event).category,
                                               (fRecord->event).severity,
                                               (fRecord->event).specificProblem,
                                               (fRecord->event).cause,
                                               CL_ALL_BUCKETS,historyRec,
                                               &recordFound);
        if(!recordFound)
        {
            /* record not found */
            fRecord->seqNum = 0;
        }
        else
        {
            /* record found */
            fRecord->seqNum = historyRec->seqNum;
        }
        rc = clFaultHistoryDataUnLock();
        if (rc != CL_OK)
        {
            clFaultCliStrPrint(ret, 
                    "REPAIR: Not able to get history data lock rc:0x%x \n", rc);
            clHeapFree(fRecord);
            clHeapFree(historyRec);
            return rc;
        }
    
        clFaultRecordPack(fRecord,ret);
        clHeapFree(fRecord);
        clHeapFree(historyRec);
    }
    else
        clFaultCliStrPrint(ret, 
                " MOId name to MOId conversion failed ..... \n");
    return CL_OK;
}
ClRcT VDECL(clDebugInvoke)(ClEoDataT        data,
                           ClBufferHandleT  inMsgHdl,
                           ClBufferHandleT  outMsgHdl)
{
    ClRcT 	              rc           = CL_OK;
    ClUint32T 	          i            = 0;
    ClUint32T 	          argc         = 0;
    ClCharT	              *argv[MAX_ARGS];
    ClCharT        	      argBuf[(MAX_ARG_BUF_LEN+1) * MAX_ARGS]; /* +1 for NULL termination */
    ClDebugObjT	          *pDebugObj   = (ClDebugObjT*) data;
    ClCharT   	          *resp        = NULL;
    ClVersionT            version      = {0};
    ClDebugInvokeCookieT  invokeCookie = {0};
    ClDebugDeferContextT  deferContext = {0};
    ClRcT                 retCode      = CL_OK;

    if ((NULL == pDebugObj) || (0 == outMsgHdl))
    {
        clLogWrite( CL_LOG_HANDLE_APP,CL_LOG_CRITICAL,CL_DEBUG_LIB_CLIENT,
                    CL_LOG_MESSAGE_0_MEMORY_ALLOCATION_FAILED);
        return CL_DEBUG_RC(CL_ERR_INVALID_PARAMETER);
    }

    rc = clXdrUnmarshallClVersionT(inMsgHdl,&version);
    if (CL_OK != rc)
    {
        return rc;
    }
    rc = clVersionVerify(&versionDatabase,&version);
    if (CL_OK != rc)
    {
        clXdrMarshallClVersionT(&version,outMsgHdl,0);
        return rc;
    }
    rc = clXdrUnmarshallClUint32T(inMsgHdl, &argc);
    if (CL_OK != rc)
    {
        return rc;
    }

    if (argc > MAX_ARGS)
    {
        DEBUG_CHECK("\r\n too many arguments");
        goto L1;
    }

    for (i = 0; i < argc; i++)
    {
        ClUint32T stringLength = 0;

        argv[i] = &argBuf[i * (MAX_ARG_BUF_LEN+1)];

        rc = clXdrUnmarshallClUint32T(inMsgHdl,&stringLength);
        if (CL_OK != rc)
        {
            return rc;
        }

        if (stringLength > MAX_ARG_BUF_LEN)
        {
            DEBUG_CHECK("\r\n argument too big");
            goto L1;
        }

        rc = clXdrUnmarshallArrayClCharT(inMsgHdl,argv[i],stringLength);
        if (CL_OK != rc)
        {
            return rc;
        }
        argv[i][stringLength] = '\0';
    }

    if (!strncasecmp(argv[0], "help", 4) && (argc > 1))
    {
        argv[0] = argv[1];
        argc = 0;
    }
    
    invokeCookie.pCommandName = argv[0];
    invokeCookie.pFuncEntry   = NULL;

    rc = clHandleWalk(pDebugObj->hDebugFnDB, clDebugFuncInvokeCallback, 
                      (void *) &invokeCookie);
    if( CL_DBG_INFO_CMD_FOUND == rc )
    {
        /* this is the indication for command found */
        rc = CL_OK;
    }
    if( CL_OK != rc )
    {
        DEBUG_CHECK("\r\ncommand not found");
        goto L1;
    }

    if (invokeCookie.pFuncEntry && invokeCookie.pFuncEntry->fpCallback)
    {
        deferContext.outMsgHdl = outMsgHdl;
        deferContext.defer = CL_FALSE;
        clOsalTaskDataSet(pDebugObj->debugTaskKey, (ClOsalTaskDataT)&deferContext);
        rc = invokeCookie.pFuncEntry->fpCallback(argc, argv, &resp);
    }
    else
    {
        DEBUG_CHECK("\r\ncommand not found");
    }

L1: 
    retCode = rc;
    rc      = CL_OK;
    if (!resp)
    {
        resp = clHeapAllocate(1);
        if (resp) resp[0]= '\0';
    }
    
    if (NULL != resp)
    {
        /*
         * Marshall the response to the out buffer if we aren't deferred.
         */
        if(!deferContext.defer)
            rc = clDebugResponseMarshall(resp, retCode, outMsgHdl);
        clHeapFree(resp);
        resp = NULL;
    }
    return rc;
}
ClRcT clCkptSvrInitialize(void)
{
    ClRcT             rc         = CL_OK;
    /* Variable related ckptDataBackup feature thats not supported
       ClUint8T          ckptRead   = 0;
    */
    ClTimerTimeOutT   timeOut    = {0}; 
    ClIocNodeAddressT deputy = 0;
    ClIocNodeAddressT master = 0;
    ClBoolT           addressUpdate = CL_FALSE;
    SaNameT           appName    = {0};   
 
    /*
     * Allocate the memory for server control block.
     */
    rc = ckptSvrCbAlloc(&gCkptSvr);
    CKPT_ERR_CHECK(CL_CKPT_SVR,CL_LOG_SEV_ERROR, 
                   ("Checkpoint service CB create failed rc[0x %x]\n", rc), rc); 

    /*
     * Mark server as not ready.
     */
    gCkptSvr->serverUp        = CL_FALSE;
    gCkptSvr->condVarWaiting  = CL_TRUE;    

    /*
     * Create condition variable that indicate the receipt
     * of master and deputy ckpt addresses from gms.
     */
    clOsalCondCreate(&gCkptSvr->condVar);
    clOsalMutexCreate(&gCkptSvr->mutexVar);
    
    gCkptSvr->masterInfo.masterAddr = CL_CKPT_UNINIT_ADDR;
    gCkptSvr->masterInfo.deputyAddr = CL_CKPT_UNINIT_ADDR;
    gCkptSvr->masterInfo.compId     = CL_CKPT_UNINIT_VALUE; 
    gCkptSvr->masterInfo.clientHdlCount = 0;
    gCkptSvr->masterInfo.masterHdlCount = 0; 

    /*
     * Initialize gms to get the master and deputy addresses.
     */
    clOsalMutexLock(&gCkptSvr->ckptClusterSem);
    rc = clCkptMasterAddressesSet();
    master = gCkptSvr->masterInfo.masterAddr;
    deputy = gCkptSvr->masterInfo.deputyAddr;
    clOsalMutexUnlock(&gCkptSvr->ckptClusterSem);

    rc = clEoMyEoObjectGet(&gCkptSvr->eoHdl);
    rc = clEoMyEoIocPortGet(&gCkptSvr->eoPort);
   
    /*
     * Install the ckpt native table.
     */
    rc = clCkptEoClientInstall();
    CL_ASSERT(rc == CL_OK);
    
    rc = clCkptEoClientTableRegister(CL_IOC_CKPT_PORT);
    CL_ASSERT(rc == CL_OK);

    /*
     * Initialize the event client library.
     */
    ckptEventSvcInitialize();
    
    /* 
     * Initialize ckpt lib for persistent memory.
     * Obtain ckptRead flag that will tell whether ckpt server needs to 
     * read data from persistent memory or not.
     */

    /*
      Feature not yet supported see bug 6017 -- Do not forget to uncomment ckptDataBackupFinalize
      rc = ckptDataBackupInitialize(&ckptRead);
    */

    if(rc != CL_OK)
    {
        clLogWrite(CL_LOG_HANDLE_APP, CL_LOG_SEV_WARNING, NULL,
                   CL_LOG_MESSAGE_2_LIBRARY_INIT_FAILED, "ckpt", rc);
    }

    if( gCkptSvr->localAddr == master )
    {
        /*
         * The node coming up is master. If deputy exists, syncup with deputy
         * else syncup with persistant memory (if existing).
         */
        rc = clCpmComponentNameGet(gCkptSvr->amfHdl, &appName);
        if(clCpmIsCompRestarted(appName))
        {
            if((deputy != CL_CKPT_UNINIT_ADDR) && ( (ClInt32T) deputy != -1))
            {
                rc = ckptMasterDatabaseSyncup(deputy);
                /*
                 * If deputy server is not reachable then pull info from the 
                 * persistent memory.
                 */
                if(CL_RMD_TIMEOUT_UNREACHABLE_CHECK(rc))
                {
                    clLogNotice(CL_CKPT_AREA_ACTIVE, "DBS", 
                                "Database Syncup with ckpt master failed with RMD timeout error. rc 0x%x",rc);
                    /* This is dead code as the feature is not supported
                       if(ckptRead == 1)
                       {
                       rc = ckptPersistentMemoryRead();
                       }
                    */
                }
            }
        }
        /* This is dead code as the feature is not supported
           else
           {
           if(ckptRead == 1)
           {
           rc = ckptPersistentMemoryRead();
           }
           }
        */
    }
    
    /*TODO:This check is only for seleting the deputy or for what */
    clOsalMutexLock(gCkptSvr->mutexVar);    
    if( (clIocLocalAddressGet() != master) &&
        (gCkptSvr->condVarWaiting == CL_TRUE)     )
    {
        /*
         * Ensure that the node gets the master and deputy addresses before
         * proceeding further.
         */
        timeOut.tsSec            = 5;
        timeOut.tsMilliSec       = 0;
        clOsalCondWait(gCkptSvr->condVar, gCkptSvr->mutexVar, timeOut);
        gCkptSvr->condVarWaiting = CL_FALSE;
        addressUpdate = CL_TRUE;
    }
    clOsalMutexUnlock(gCkptSvr->mutexVar);    

    /*  
     * We double check again incase we had waited for the gms cluster track.
     * but with the right lock sequence below instead of shoving it in the
     * condwait above.
     */
    if(addressUpdate == CL_TRUE)
    {
        clOsalMutexLock(&gCkptSvr->ckptClusterSem);
        master = gCkptSvr->masterInfo.masterAddr;
        deputy = gCkptSvr->masterInfo.deputyAddr;
        clOsalMutexUnlock(&gCkptSvr->ckptClusterSem);
    }
    /* 
     * Announce the arrival to peer in the n/w. Master server announces to 
     * all and other servers announce to master server.
     */
    ckptSvrArrvlAnnounce();
    
    /*
     * If the node coming up is deputy, syncup the metadata and ckpt info 
     * from the master. Treat all SC capable nodes except the master as deputy.
     */
    if(  gCkptSvr->localAddr != master && clCpmIsSCCapable())
    {
        /*
         * Just freezing the deputy till syncup, not to receive any master
         * related calls, this is to ensure that deputy is in full synup with
         * master and any calls from master to update deputy will sleep on the
         * lock.
         */
        CKPT_LOCK(gCkptSvr->masterInfo.ckptMasterDBSem);
        ckptMasterDatabaseSyncup(gCkptSvr->masterInfo.masterAddr);
        CKPT_UNLOCK(gCkptSvr->masterInfo.ckptMasterDBSem);
    }
    
    /* 
     * Server is up.
     */
    gCkptSvr->serverUp = CL_TRUE;
    return rc;
    exitOnError:
    {
        return rc;
    }
}
/** 
 *  Class Type create API.
 *
 *  Creates a new class type with the given information like class id,
 *  number of attributes, max and minimum instances for the class.
 *  NOTE: What happens in case of different versions?? need to figure
 *  out.
 *
 *  @param id            class id
 *  @param nAttrs        Number of attributes in class.
 *
 *  @returns 
 *    CORClass_h   (non-null) valid class handle
 *      null(0)    on failure.
 * 
 */
ClRcT
dmClassCreate(ClCorClassTypeT id,
              ClCorClassTypeT inhId)
{
    CORClass_h tmp = 0;
    CORClass_h tmp1 = 0;
    ClRcT ret = CL_OK;

    CL_FUNC_ENTER();

    if(!dmGlobal)
    {
        CL_FUNC_EXIT();  
        return(CL_COR_SET_RC(CL_COR_ERR_NULL_PTR));
    }
    
    CL_DEBUG_PRINT(CL_DEBUG_TRACE, ( "ClassCreate (Class:%04x, Inh:%04x)", id, inhId));
    
    /* check if id & inhId is already present 
     */
    HASH_GET(dmGlobal->classTable, id, tmp);
    if(inhId > 0) 
    {
        HASH_GET(dmGlobal->classTable, inhId, tmp1);
    }
    
    if(tmp) 
    {
        CL_DEBUG_PRINT(CL_DEBUG_TRACE, ( "ClassCreate (Class:%04x, Inh:%04x) [Class present]", id, inhId));
        ret = CL_COR_SET_RC(CL_COR_ERR_CLASS_PRESENT);
    } 
    else if(tmp1 == 0 && inhId > 0) 
    {
        CL_DEBUG_PRINT(CL_DEBUG_ERROR, ( "ClassCreate (Class:%04x, Inh:%04x) [Superclass unknown]", id, inhId));
        ret = CL_COR_SET_RC(CL_COR_ERR_CLASS_NOT_PRESENT);
    } 
    else 
    {
        /* Create the new class
         */
        tmp = (CORClass_h) clHeapAllocate(sizeof(CORClass_t));
        if(tmp != 0) 
        {
            /* init stuff here */
            tmp->classId = id;
            tmp->superClassId = inhId; 
            tmp->size = -1;
            tmp->version.releaseCode = CL_RELEASE_VERSION;
            tmp->version.majorVersion = CL_MAJOR_VERSION;
            tmp->version.minorVersion = CL_MINOR_VERSION;
            tmp->flags = 0;
            tmp->moClassInstances = 0;

            if (CL_OK != (ret = HASH_CREATE(&tmp->attrList)))
            { 
                  clHeapFree(tmp);
                  CL_DEBUG_PRINT(CL_DEBUG_ERROR, ( "Failed to create hash table for Attributes [rc 0x%x]", ret));
                  CL_FUNC_EXIT();  
                  return (ret);
            }
        
            if (CL_OK != (ret = COR_LLIST_CREATE(&tmp->objFreeList)))
            {
                clHeapFree(tmp);
                CL_DEBUG_PRINT(CL_DEBUG_ERROR, ( "Failed to create hash table for free objects [rc 0x%x]", ret));
                CL_FUNC_EXIT();
                return (ret);
            }

            tmp->nAttrs = 0;
            tmp->noOfChildren = 0;
            tmp->recordId = 1;
            tmp->objCount = 0;
            tmp->objBlockSz = COR_OBJ_DEF_BLOCK_SIZE;

            /* init the vector, check the return value
             * and remove class/hashtable
             */
            if (CL_OK != (ret = corVectorInit(&tmp->attrs, 
                          sizeof(CORAttr_t),
                          COR_CLASS_DEF_BLOCK_SIZE)))
            {
                HASH_FREE(tmp->attrList);
                COR_LLIST_FREE(tmp->objFreeList);
                clHeapFree(tmp);
    	        CL_FUNC_EXIT();  
     	        return (ret);
	        }

            /* add the newly created class to the class table */
            if (CL_OK != (ret = HASH_PUT(dmGlobal->classTable, id, tmp)))
	        {
              corVectorRemoveAll(&tmp->attrs);
              HASH_FREE(tmp->attrList);
              COR_LLIST_FREE(tmp->objFreeList);
              clHeapFree(tmp);
       	      CL_DEBUG_PRINT(CL_DEBUG_ERROR, ( "Failed to add class in Data Manager [rc 0x%x]", ret));
    	      CL_FUNC_EXIT();  
     	      return (ret);
	        }
            /* declare the inh class as base class */
            if(inhId > 0) 
            {
                tmp1->noOfChildren++;
                COR_CLASS_SETAS_BASE(*tmp1);
            }
        } 
        else 
        {
	        clLogWrite(CL_LOG_HANDLE_APP, CL_LOG_DEBUG, NULL,
				CL_LOG_MESSAGE_0_MEMORY_ALLOCATION_FAILED);
                CL_DEBUG_PRINT(CL_DEBUG_CRITICAL, (CL_COR_ERR_STR_MEM_ALLOC_FAIL)); 
            ret = CL_COR_SET_RC(CL_COR_ERR_NO_MEM);
        }
    }

    CL_FUNC_EXIT();  
    return (ret);
}
/**
 * API to register a service with transaction agent
 */
ClRcT clTxnAgentServiceRegister(
        CL_IN   ClInt32T                    serviceId, 
        CL_IN   ClTxnAgentCallbacksT        tCallback, 
        CL_OUT  ClTxnAgentServiceHandleT    *pHandle)
{
    /*
       This is registration request from a service hosted in this component.
       (There could be multiple such services).
       Store these callbacks in an appropriate data-structure indexed with 
       service-id (identication of service under considered).
    */
    ClRcT                       rc                  = CL_OK;
    ClUint8T                    serviceCapability   = 0xFF;
    ClTxnAgentCompServiceInfoT  *pNewCompService    = NULL;

    CL_FUNC_ENTER();

    CL_TXN_NULL_CHECK_RETURN(pHandle, CL_ERR_NULL_POINTER, ("Invalid handle\n"));
    if (NULL == clTxnAgntCfg)
    {
        clLogWrite(CL_LOG_HANDLE_APP, CL_LOG_ERROR, CL_TXN_AGENT_LIB,
                   CL_LOG_MESSAGE_0_COMPONENT_UNINITIALIZED);
        CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("Agent library is not initialized. clTxnAgntCfg is NULL\n"));
        CL_FUNC_EXIT();
        return CL_TXN_RC(CL_ERR_NOT_INITIALIZED);
    }

    /* Validate callback function */
    if( (tCallback.fpTxnAgentJobPrepare == NULL) && 
        (tCallback.fpTxnAgentJobRollback == NULL) &&
        (tCallback.fpTxnAgentJobCommit != NULL) )
    {
        serviceCapability = CL_TXN_AGENT_SERVICE_1PC;
        clTxnMutexLock(clTxnAgntCfg->actMtx);
        /* Check if this is not the first one to declare as 1-PC Capable service */
        if ( (clTxnAgntCfg->agentCapability & 
                CL_TXN_AGENT_SERVICE_1PC) == CL_TXN_AGENT_SERVICE_1PC)
        {
            CL_DEBUG_PRINT(CL_DEBUG_ERROR, 
                    ("Txn-Agent does not allow more than one service of 1-PC Type"));
            CL_FUNC_EXIT();
            clTxnMutexUnlock(clTxnAgntCfg->actMtx);
            return CL_TXN_RC(CL_ERR_INVALID_PARAMETER);
        }
        clTxnMutexUnlock(clTxnAgntCfg->actMtx);
    }
    else if ( (tCallback.fpTxnAgentJobPrepare != NULL) &&
              (tCallback.fpTxnAgentJobCommit != NULL)  &&
              (tCallback.fpTxnAgentJobRollback != NULL) )
    {
        serviceCapability = CL_TXN_AGENT_SERVICE_2PC;
    }
    else
    {
        CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("Invalid parameter - callback function not defined properly"));
        CL_FUNC_EXIT();
        return CL_TXN_RC(CL_ERR_INVALID_PARAMETER);
    }

    /* Check if entry already exists or not */
    rc = clCntDataForKeyGet( (ClCntHandleT) clTxnAgntCfg->compServiceMap, 
                              (ClCntKeyHandleT) &serviceId, 
                              (ClCntDataHandleT *) &pNewCompService);
    if ( CL_OK == rc )
    {
        CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("Component-service already registered\n"));
        CL_FUNC_EXIT();
        return (CL_TXN_RC(CL_ERR_DUPLICATE));
    }

    pNewCompService = (ClTxnAgentCompServiceInfoT *) clHeapAllocate(sizeof(ClTxnAgentCompServiceInfoT));
    CL_TXN_NULL_CHECK_RETURN(pNewCompService, CL_ERR_NO_MEMORY, 
                             ("Failed to allocate memory\n"));

    memset(pNewCompService, 0, sizeof(ClTxnAgentCompServiceInfoT));
    pNewCompService->serviceType = serviceId;
    pNewCompService->serviceCapability = serviceCapability;

    pNewCompService->pCompCallbacks = 
        (ClTxnAgentCallbacksT *) clHeapAllocate(sizeof(ClTxnAgentCallbacksT));
    
    
    CL_TXN_NULL_CHECK_RETURN(pNewCompService->pCompCallbacks, CL_ERR_NO_MEMORY,
                             ("Failed to allocate memory\n"));
    memcpy(pNewCompService->pCompCallbacks, &tCallback, sizeof(ClTxnAgentCallbacksT));

    /* Put the entry into hash-map with service-id to be the key */
    rc = clCntNodeAdd(clTxnAgntCfg->compServiceMap, 
                       (ClCntKeyHandleT) &(pNewCompService->serviceType), 
                       (ClCntDataHandleT)pNewCompService, NULL);

    if (CL_OK != rc)
    {
        clHeapFree(pNewCompService->pCompCallbacks);
        clHeapFree(pNewCompService);
    }
    else 
    {
        /* Update agent-cfg */
        if (serviceCapability == CL_TXN_AGENT_SERVICE_1PC)
        {
#ifdef CL_TXN_DEBUG
            CL_DEBUG_PRINT(CL_DEBUG_ERROR,( "Service registered is 1pc\n"));
#endif
            clTxnAgntCfg->agentCapability |= CL_TXN_AGENT_SERVICE_1PC;
        }
        else
            clTxnAgntCfg->agentCapability |= CL_TXN_AGENT_SERVICE_2PC;

        *pHandle = (ClTxnAgentServiceHandleT )pNewCompService;
        clLogNotice("AGT", "INI",
                "Registered [%s] service successfully having serviceId [%d]", 
                (serviceCapability == CL_TXN_AGENT_SERVICE_1PC)?"READ": "2P",
                serviceId);
    }
    CL_TXN_RETURN_RC(rc, ("Failed to register new component-service rc:0x%x\n", rc));
}
ClRcT clDebugRegister(ClDebugFuncEntryT  *funcArray,
                      ClUint32T          funcArrayLen,
                      ClHandleT          *phDebugReg)/* - by user - needs to be exposed*/
{
    ClRcT              rc          = CL_OK;
    ClDebugObjT        *pDebugObj  = NULL;
    ClUint32T          i           = 0;
    ClEoExecutionObjT  *pEoObj     = NULL; 
    ClDebugFuncGroupT  *pFuncGroup = NULL;

    if ((0 == funcArrayLen) || (NULL == funcArray))
    {
        clLogWrite(CL_LOG_HANDLE_APP,CL_LOG_WARNING,CL_DEBUG_LIB_CLIENT,
                   CL_LOG_MESSAGE_1_INVALID_PARAMETER,"Arguments are Invalid");
        return CL_DEBUG_RC(CL_ERR_INVALID_PARAMETER);
    }

    rc = clEoMyEoObjectGet(&pEoObj);
    if (CL_OK != rc)
    {
        CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("clEoMyEoObjectGet(): rc[0x %x]",
                    rc));
        return rc;
    }
    rc = clEoPrivateDataGet( pEoObj,
                             CL_EO_DEBUG_OBJECT_COOKIE_ID,
                             (void**) &pDebugObj);
    if (CL_OK != rc)
    {
        return rc;
    }
    
     /* Detecting dupilcate entries are there or not */
    rc = clDebugDuplicateCommandDetect(pDebugObj, funcArray, funcArrayLen);
    if( CL_OK != rc )
    {
        return rc;
    }

    rc = clHandleCreate(pDebugObj->hDebugFnDB, sizeof(ClDebugFuncGroupT), phDebugReg);
    if( CL_OK != rc )
    {
        CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("clHandleCreate(): rc[0x %x]", rc));
        return rc;
    }

    rc = clHandleCheckout(pDebugObj->hDebugFnDB, *phDebugReg, 
                          (void **) &pFuncGroup);
    if( CL_OK != rc )
    {
        CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("clHandleCheckout(): rc[0x %x]", rc));
        clHandleDestroy(pDebugObj->hDebugFnDB, *phDebugReg);
        return rc;
    }

    pFuncGroup->pFuncDescList = clHeapAllocate(sizeof(ClDebugFuncEntryT) *
                                                         funcArrayLen);
    if (NULL == pFuncGroup->pFuncDescList)
    {
        clLogWrite(CL_LOG_HANDLE_APP,CL_LOG_CRITICAL,CL_DEBUG_LIB_CLIENT,
                   CL_LOG_MESSAGE_0_MEMORY_ALLOCATION_FAILED);
        clHandleCheckin(pDebugObj->hDebugFnDB, *phDebugReg);
        clHandleDestroy(pDebugObj->hDebugFnDB, *phDebugReg);
        return CL_DEBUG_RC(CL_ERR_NO_MEMORY);
    }

    for (i = 0; i < funcArrayLen; i++)
    {
         pFuncGroup->pFuncDescList[i] = funcArray[i];
    }

    pFuncGroup->numFunc = funcArrayLen;
    pDebugObj->numFunc += pFuncGroup->numFunc;
    if( CL_OK != (rc = clHandleCheckin(pDebugObj->hDebugFnDB, *phDebugReg)))
    {
        CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("clHandleCheckin(): rc[0x %x]", rc));
    }

    return CL_OK;
}
ClRcT VDECL(clDebugGetContext)(ClEoDataT        data,
                               ClBufferHandleT  inMsgHdl,
                               ClBufferHandleT  outMsgHdl)
{
    ClRcT        rc         = CL_OK;
    ClDebugObjT  *pDebugObj = (ClDebugObjT *) data;
    ClVersionT   version    = {0};
    ClIocPhysicalAddressT srcAddr = {0};

    if ((NULL == pDebugObj) || (0 == outMsgHdl) || (0 == inMsgHdl))
    {
        clLogWrite(CL_LOG_HANDLE_APP,CL_LOG_WARNING,CL_DEBUG_LIB_CLIENT,
                   CL_LOG_MESSAGE_1_INVALID_PARAMETER,"Invalid debugObj");
        return CL_DEBUG_RC(CL_ERR_INVALID_PARAMETER);
    }

    /*
     * Enable the comp status for the debug client to avoid
     * response failures from node representative in case the bit isnt enabled for cases when
     * the comp arrival from peer noderep. reaches late.
     */
    if(clRmdSourceAddressGet(&srcAddr) == CL_OK)
        clIocCompStatusEnable(srcAddr);
    
    rc = clXdrUnmarshallClVersionT(inMsgHdl,&version);
    if (CL_OK != rc)
    {
        return rc;
    }
    rc = clVersionVerify(&versionDatabase,&version);
    if (CL_OK != rc)
    {
        clXdrMarshallClVersionT(&version,outMsgHdl,0);
        return rc;
    }

    rc = clXdrMarshallArrayClCharT(pDebugObj->compName,
                                   CL_DEBUG_COMP_NAME_LEN,
                                   outMsgHdl,0);
    if (CL_OK != rc)
    {
        return rc;
    }

    rc = clXdrMarshallArrayClCharT(pDebugObj->compPrompt,
                                   CL_DEBUG_COMP_PROMPT_LEN,
                                   outMsgHdl,0);
    if (CL_OK != rc)
    {
        return rc;
    }

    rc = clXdrMarshallClUint32T((&pDebugObj->numFunc),
                                outMsgHdl,0);
    if (CL_OK != rc)
    {
        return rc;
    }

    rc = clHandleWalk(pDebugObj->hDebugFnDB, clDebugContexDetailsPack,
                      (ClPtrT) outMsgHdl);
    if( CL_OK != rc )
    {
        return rc;
    }

    return rc;
}
ClRcT clDebugLibInitialize(void)
{
    ClEoExecutionObjT  *pEoObj     = NULL;
    ClDebugObjT        *pDebugObj  = NULL;
    ClRcT              rc          = CL_OK;
    ClNameT            compName    = {0};
    
    rc = clEoMyEoObjectGet(&pEoObj);
    if (CL_OK != rc)
    {
        return rc;
    }

    pDebugObj = clHeapCalloc(1, sizeof(ClDebugObjT));
    if (NULL == pDebugObj)
    {
        clLogWrite(CL_LOG_HANDLE_APP,CL_LOG_CRITICAL,CL_DEBUG_LIB_CLIENT,
                   CL_LOG_MESSAGE_0_MEMORY_ALLOCATION_FAILED);
        return CL_DEBUG_RC(CL_ERR_NO_MEMORY);
    }

    rc = clOsalTaskKeyCreate(&pDebugObj->debugTaskKey, NULL);
    if(rc != CL_OK)
    {
        CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("Debug task key create returned with [%#x]\n", rc));
        clHeapFree(pDebugObj);
        return CL_DEBUG_RC(CL_GET_ERROR_CODE(rc));
    }

    rc = clHandleDatabaseCreate(NULL, &pDebugObj->hDebugFnDB);
    if( CL_OK != rc )
    {
        CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("clHandleDatabaseCreate(): rc[0x %x]",
                rc));
        clHeapFree(pDebugObj);
        return CL_DEBUG_RC(CL_ERR_NO_MEMORY);
    }

    /* Getting the compName from CPM */
    rc = clCpmComponentNameGet(0, &compName);
    if( CL_OK != rc )
    {
        CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("clCpmComponentNameGet(): rc[0x %x]",
                    rc));
        clLogWrite(CL_LOG_HANDLE_APP,CL_LOG_WARNING,CL_DEBUG_LIB_CLIENT,
                   CL_LOG_MESSAGE_1_INVALID_PARAMETER, 
                   "CompNameGet is not proper");
        return rc;
    }

    pDebugObj->numFunc       = 0;
    /* Assining the compName */
    memset(pDebugObj->compName, '\0', CL_DEBUG_COMP_NAME_LEN);
    if( compName.length < CL_DEBUG_COMP_NAME_LEN )
    {
        memcpy(pDebugObj->compName, compName.value, compName.length);
        pDebugObj->compName[compName.length] = '\0';
    }
    else
    {
        clLogWrite(CL_LOG_HANDLE_APP,CL_LOG_WARNING,CL_DEBUG_LIB_CLIENT,
                   CL_LOG_MESSAGE_1_INVALID_PARAMETER,"CompName is Invalid");
        return CL_DEBUG_RC(CL_ERR_INVALID_PARAMETER);
    }

    /* Assigning compPrompt to DEFAULT */
    memset(pDebugObj->compPrompt, '\0', CL_DEBUG_COMP_PROMPT_LEN);
    strcpy(pDebugObj->compPrompt, "DEFAULT");

    rc = clEoClientInstallTablesWithCookie( pEoObj, 
                                            CL_EO_SERVER_SYM_MOD(gAspFuncTable, DEBUGCli),
                                            pDebugObj);
    if (CL_OK != rc)
    {
        CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("clEoClientInstall(): rc[0x %x]", rc));
        clHandleDatabaseDestroy(pDebugObj->hDebugFnDB);
        clHeapFree(pDebugObj);
        return rc;
    }
    rc = clDebugClientTableRegister(pEoObj);
    if(CL_OK != rc)
    {
        clEoClientUninstallTables(pEoObj, 
                                  CL_EO_SERVER_SYM_MOD(gAspFuncTable, DEBUGCli));
        clHandleDatabaseDestroy(pDebugObj->hDebugFnDB);
        clHeapFree(pDebugObj);
        return rc;
    }

    rc = clEoPrivateDataSet(pEoObj, CL_EO_DEBUG_OBJECT_COOKIE_ID, pDebugObj);
    if (CL_OK != rc)
    {
        CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("clEoPrivateDataSet(): rc[0x %x]", rc));
        clEoClientUninstallTables(pEoObj, 
                                  CL_EO_SERVER_SYM_MOD(gAspFuncTable, DEBUGCli));
        clHandleDatabaseDestroy(pDebugObj->hDebugFnDB);
        clHeapFree(pDebugObj);
        return rc;
    }
    
    clEoDebugRegister();

    return rc;
}
ClRcT 
clFaultHistoryInit(ClUint32T binNumbers){

   ClRcT          rc = CL_OK;
   ClTimerTimeOutT      timeOut;


   /* fault history containers can be accessed by FM thread, timer thread
    * etc .. So before accessing the containers, the threads shd take the
    * mutex
    */
    rc = clOsalMutexCreateAndLock(&shfaultHistoryMutex);
    if (rc != CL_OK)
    {
        clLogWrite(CL_LOG_HANDLE_APP, 
               CL_LOG_ERROR,   
               CL_FAULT_SERVER_LIB,
               CL_FAULT_LOG_1_MUTEX,
               "Fault History data base");
      return CL_FAULT_ERR_HISTORY_MUTEX_CREATE_ERROR;
    }

   /* 
    * Create a circular queue with number of nodes = binNumbers
    * Each node is a linked list of fault recovery/history record 
       sorted by key composed of category and severity
    */
   /*
    * Create a repetitive timer at frequency interval = binInterval
    */

   rc = clClistCreate( MAX_FAULT_BUCKETS,
                          CL_DROP_FIRST,
                           (ClClistDeleteCallbackT) clFaultHis2MinBucketDelete,
                           (ClClistDeleteCallbackT) clFaultHis2MinBucketDelete,
                           &sfaultHistoryList);

   if (rc != CL_OK ) 
   {
      clLogError("FLT", NULL, "Error in creating Clist, rc [0x%x]", 
              rc);
      goto unlock_exit;
   }


   /* start a 2 minute timer */
    timeOut.tsSec = binNumbers;
    timeOut.tsMilliSec = 0; 

    if ((rc = clTimerCreate(timeOut,
                              CL_TIMER_REPETITIVE,
                              CL_TIMER_SEPARATE_CONTEXT, 
                              (ClTimerCallBackT) clFault2MinHistoryCallback,
                              NULL, 
                              &sFaultMan2MinHistoryTimerH)
                            ) != CL_OK)
   {
     clLogError("FLT", NULL, "Failed to create repetitive timer for \
                            fault manager's 2 min history");
      goto unlock_exit;
    }
static void cpmMakeSCActiveOrDeputy(const ClGmsClusterNotificationBufferT *notificationBuffer,
                                    ClCpmLocalInfoT *pCpmLocalInfo)
{
    ClUint32T rc = CL_OK;
    ClGmsNodeIdT prevMasterNodeId = gpClCpm->activeMasterNodeId;
    ClBoolT leadershipChanged = notificationBuffer->leadershipChanged;
    
    /*  
     * Check for initial leadership state incase the cluster track from AMF was issued
     * after GMS leader election was done and GMS responded back with a track with a leadership changed
     * set to FALSE for a CURRENT async request from AMF.
     */
    if(leadershipChanged == CL_FALSE && 
       (ClInt32T) notificationBuffer->leader == pCpmLocalInfo->nodeId &&
       (ClInt32T) prevMasterNodeId != pCpmLocalInfo->nodeId && 
       gpClCpm->haState == CL_AMS_HA_STATE_NONE)
        leadershipChanged = CL_TRUE;
        
    if (leadershipChanged == CL_TRUE)
    {
        if ( (ClInt32T) notificationBuffer->leader == pCpmLocalInfo->nodeId)
        {
            clLogInfo(CPM_LOG_AREA_CPM, CPM_LOG_CTX_CPM_GMS,
                      "Node [%d] has become the leader of the cluster",
                      pCpmLocalInfo->nodeId);

            if(gpClCpm->haState != CL_AMS_HA_STATE_ACTIVE)
            {
                rc = cpmUpdateTL(CL_AMS_HA_STATE_ACTIVE);
                if (rc != CL_OK)
                {
                    clLogWrite(CL_LOG_HANDLE_APP, CL_LOG_SEV_DEBUG, NULL,
                               CL_CPM_LOG_1_TL_UPDATE_FAILURE, rc);
                }
            }
            gpClCpm->deputyNodeId = notificationBuffer->deputy;
        }
        else if ((ClInt32T) notificationBuffer->deputy == pCpmLocalInfo->nodeId)
        {
            clLogInfo(CPM_LOG_AREA_CPM, CPM_LOG_CTX_CPM_GMS,
                      "Node [%d] has become the deputy of the cluster",
                      pCpmLocalInfo->nodeId);
            /*
             * Deregister the active registration if going from active to standby.
             */
            if(gpClCpm->haState == CL_AMS_HA_STATE_ACTIVE)
            {
                clIocTransparencyDeregister(pCpmLocalInfo->nodeId << CL_CPM_IOC_SLOT_BITS);
            }
            rc = cpmUpdateTL(CL_AMS_HA_STATE_STANDBY);
            if (rc != CL_OK)
            {
                clLogWrite(CL_LOG_HANDLE_APP, CL_LOG_SEV_DEBUG, NULL,
                           CL_CPM_LOG_1_TL_UPDATE_FAILURE, rc);
            }
        }

        if ((gpClCpm->haState == CL_AMS_HA_STATE_ACTIVE) && 
            ( (ClInt32T) notificationBuffer->leader != pCpmLocalInfo->nodeId))
        {
            clLogDebug(CPM_LOG_AREA_CPM, CPM_LOG_CTX_CPM_GMS,
                       "Node [%d] is changing HA state from active to standby",
                       pCpmLocalInfo->nodeId);
              
            /*
             * Deregister the entry during a state change.
             */
            if ( (ClInt32T) notificationBuffer->deputy != pCpmLocalInfo->nodeId)
            {
                clIocTransparencyDeregister((pCpmLocalInfo->nodeId) << CL_CPM_IOC_SLOT_BITS);
            }

            /*
             * Inform AMS to become standby and read the checkpoint.
             */
            if ((gpClCpm->cpmToAmsCallback != NULL) && 
                (gpClCpm->cpmToAmsCallback->amsStateChange != NULL))
            {
                clLogDebug(CPM_LOG_AREA_CPM, CPM_LOG_CTX_CPM_GMS,
                           "Informing AMS on node [%d] to change state "
                           "from active to standby...",
                           pCpmLocalInfo->nodeId);

                rc = gpClCpm->cpmToAmsCallback->amsStateChange(CL_AMS_STATE_CHANGE_ACTIVE_TO_STANDBY |
                                                               CL_AMS_STATE_CHANGE_USE_CHECKPOINT);
                if (CL_OK != rc)
                {
                    clLogWarning(CPM_LOG_AREA_CPM, CPM_LOG_CTX_CPM_AMS,
                                 "AMS state change from active to standby "
                                 "returned [%#x]",
                                 rc);
                }

                cpmWriteNodeStatToFile("AMS", CL_NO);

                if(!gClAmsSwitchoverInline)
                {
                    if (((notificationBuffer->numberOfItems == 0) &&
                         (notificationBuffer->notification == NULL)) &&
                        gpClCpm->polling &&
                        (gpClCpm->nodeLeaving == CL_FALSE))
                    {
                        /*
                         * This indicates that leader election API of
                         * GMS was called.  Since this involves
                         * interaction among only system controllers,
                         * we don't need to restart the worker nodes
                         * like in the case of split brain handling.
                         */
                        
                        cpmActive2Standby(CL_NO);
                    }
                    else if (( (ClInt32T) notificationBuffer->deputy == pCpmLocalInfo->nodeId) && gpClCpm->polling && (gpClCpm->nodeLeaving == CL_FALSE))
                    {
                        /*
                         * We try and handle a possible split brain
                         * since presently GMS shouldnt be reelecting.
                         * And even if it does, its pretty much
                         * invalid with respect to AMS where you could
                         * land up with 2 actives.
                         */
                     
                        /*
                         * We arent expected to return back.
                         */
                        cpmActive2Standby(CL_NO);
                    }
                }
            }

            /*
             * Bug 4168:
             * Updating the data structure gpClCpm, when the active becomes
             * standby.
             */
            gpClCpm->haState = CL_AMS_HA_STATE_STANDBY;
            gpClCpm->activeMasterNodeId = notificationBuffer->leader;
            gpClCpm->deputyNodeId = notificationBuffer->deputy;
            if(gClAmsSwitchoverInline)
            {
                /*
                 *Re-register with active.
                 */
                clOsalMutexUnlock(&gpClCpm->clusterMutex);
                cpmSwitchoverActive();
                clOsalMutexLock(&gpClCpm->clusterMutex);
            }
        }
        else if ((gpClCpm->haState == CL_AMS_HA_STATE_STANDBY) && 
                 ( (ClInt32T) notificationBuffer->leader == pCpmLocalInfo->nodeId))
        {
            rc = cpmStandby2Active(prevMasterNodeId, 
                                   notificationBuffer->deputy);
            if (CL_OK != rc)
            {
                return;
            }
        }
        else if ((gpClCpm->haState == CL_AMS_HA_STATE_NONE) && 
                 ( (ClInt32T) notificationBuffer->leader ==
                  pCpmLocalInfo->nodeId))
        {
            /*
             * Bug 4411:
             * Added the if-else block.
             * Calling the AMS initialize only if both the callback pointers
             * are not NULL.
             * FIXME: This change is sort of workaround for 2.2.
             * Neat solution is to protect gpClCpm structure and fields properly
             */
            if ((gpClCpm->amsToCpmCallback != NULL) &&
                (gpClCpm->cpmToAmsCallback != NULL))
            {
                clLogDebug(CPM_LOG_AREA_CPM, CPM_LOG_CTX_CPM_AMS,"Starting AMS in active mode...");

                rc = clAmsStart(&gAms,CL_AMS_INSTANTIATE_MODE_ACTIVE | CL_AMS_INSTANTIATE_USE_CHECKPOINT);
                /*
                 * Bug 4092:
                 * If the AMS intitialize fails then do the 
                 * self shut down.
                 */
                if (CL_OK != rc)
                {
                    clLogCritical(CPM_LOG_AREA_CPM, CPM_LOG_CTX_CPM_AMS,"Unable to initialize AMF, error = [%#x]", rc);

                    gpClCpm->amsToCpmCallback = NULL;
                    cpmReset(NULL,NULL);
                    return;
                }
            }
            else
            {
                rc = CL_CPM_RC(CL_ERR_NULL_POINTER);
                 
                if (!gpClCpm->polling)
                {
                    clLogCritical(CPM_LOG_AREA_CPM, CPM_LOG_CTX_CPM_AMS, "AMF finalize called before AMF initialize during node shutdown.");
                }
                else
                {
                    clLogCritical(CPM_LOG_AREA_CPM, CPM_LOG_CTX_CPM_AMS, "Unable to initialize AMF, error = [%#x]", rc);
                     
                    cpmRestart(NULL,NULL);
                }
                return;
            }
             
            gpClCpm->haState = CL_AMS_HA_STATE_ACTIVE;
            gpClCpm->activeMasterNodeId = notificationBuffer->leader;
            gpClCpm->deputyNodeId = notificationBuffer->deputy;
        }
        /*
         * There could be more than 1 standby SC. 
         * Every none HA-state SC except the master is updated to become to standby SC.        
         */
        else if (gpClCpm->haState == CL_AMS_HA_STATE_NONE)
        {
            /*
             * Bug 4411:
             * Added the if-else block.
             * Calling the clAmsStart only if both the callback pointers
             * are not NULL.
             * FIXME: This change is sort of workaround for 2.2.
             * Neat solution is to protect gpClCpm structure and fields properly
             */
            if ((gpClCpm->amsToCpmCallback != NULL) &&
                (gpClCpm->cpmToAmsCallback != NULL))
            {
                clLogDebug(CPM_LOG_AREA_CPM, CPM_LOG_CTX_CPM_AMS,
                           "Starting AMS in standby mode...");

                rc = clAmsStart(&gAms,CL_AMS_INSTANTIATE_MODE_STANDBY);
                /*
                 * Bug 4092:
                 * If the AMS initialize fails then do the 
                 * self shut down.
                 */
                if (CL_OK != rc)
                {
                    clLogCritical(CPM_LOG_AREA_CPM, CPM_LOG_CTX_CPM_AMS,"Unable to initialize AMS, error = [%#x]", rc);

                    gpClCpm->amsToCpmCallback = NULL;
                    cpmRestart(NULL,NULL);
                    return;
                }
            }
            else
            {
                rc = CL_CPM_RC(CL_ERR_NULL_POINTER);
                 
                if (!gpClCpm->polling)
                {
                    clLogCritical(CPM_LOG_AREA_CPM, CPM_LOG_CTX_CPM_AMS,"AMS finalize called before AMS initialize during node shutdown.");
                }
                else
                {
                    clLogCritical(CPM_LOG_AREA_CPM, CPM_LOG_CTX_CPM_AMS,"Unable to initialize AMS, error = [%#x]", rc);
                    cpmRestart(NULL,NULL);
                }
                return;
            }

            gpClCpm->haState = CL_AMS_HA_STATE_STANDBY;
            gpClCpm->activeMasterNodeId = notificationBuffer->leader;
            gpClCpm->deputyNodeId = notificationBuffer->deputy;
            if(gpClCpm->bmTable->currentBootLevel == pCpmLocalInfo->defaultBootLevel)
            {
                cpmInitializeStandby();
            }
        }
        else
        {
            gpClCpm->activeMasterNodeId = notificationBuffer->leader;
            gpClCpm->deputyNodeId = notificationBuffer->deputy;
        }

        clLogNotice(CPM_LOG_AREA_CPM, CPM_LOG_CTX_CPM_CPM,
                    "HA state of node [%s] with node ID [%d] is [%s], "
                    "Master node is [%d]",
                    pCpmLocalInfo->nodeName,
                    pCpmLocalInfo->nodeId,
                    gpClCpm->haState == CL_AMS_HA_STATE_ACTIVE  ? "Active":
                    gpClCpm->haState == CL_AMS_HA_STATE_STANDBY ? "Standby":
                    "None",
                    gpClCpm->activeMasterNodeId);
    }
    else
    {
        /*
         * Always update the deputy node ID.  It may be that this
         * path is reached because a deputy node failed.
         */
        gpClCpm->deputyNodeId = notificationBuffer->deputy;

        if (CL_CPM_IS_ACTIVE())
        {
            if(notificationBuffer->notification && 
               notificationBuffer->numberOfItems == 1)
            {

                if (CL_GMS_NODE_LEFT ==
                    notificationBuffer->notification->clusterChange)
                {
                    cpmFailoverNode(notificationBuffer->notification->
                                    clusterNode.nodeId, CL_FALSE);
                }
                else
                {
                    clLogNotice(CPM_LOG_AREA_CPM, CPM_LOG_CTX_CPM_AMS, 
                                "Ignoring notification of type [%d] for node [%d]",
                                notificationBuffer->notification->clusterChange,
                                notificationBuffer->notification->clusterNode.nodeId);
                }
            }
            else if(notificationBuffer->notification)
            {
                clLogNotice(CPM_LOG_AREA_CPM, CPM_LOG_CTX_CPM_AMS, 
                            "Ignoring notification with number of items [%d], first type [%d]",
                            notificationBuffer->numberOfItems,
                            notificationBuffer->notification->clusterChange);
            }
        }
        else if ((gpClCpm->haState == CL_AMS_HA_STATE_NONE) && ( (ClInt32T) notificationBuffer->deputy == pCpmLocalInfo->nodeId))
        {
            if(CL_GMS_NODE_JOINED ==
               notificationBuffer->notification->clusterChange)
            {
                cpmStandbyRecover(notificationBuffer);
            }
            else if(gpClCpm->bmTable->currentBootLevel == pCpmLocalInfo->defaultBootLevel)
            {
                cpmStandbyRecover(notificationBuffer);
                cpmInitializeStandby();
            }
        }
    }
    return ;
}