Exemplo n.º 1
0
int main( int argc, char *argv[] )
{
	int fd = 0;
	int opt, opt_index;
	int result = -1;
	long bufSize = 0; 
	// long writtenSize;
	int writtenSize = 0;
	long writtenSize_long = 0;
	char *bufTop = NULL;
	CNCL_P_SETTINGS Settings;
	char jobID[CN_START_JOBID_LEN];
	char libPathBuf[CN_LIB_PATH_LEN];
	void *libclss = NULL;
	struct option long_opt[] = {
		{ "version", required_argument, NULL, OPT_VERSION }, 
		{ "filterpath", required_argument, NULL, OPT_FILTERPATH }, 
		{ "papersize", required_argument, NULL, OPT_PAPERSIZE }, 
		{ "mediatype", required_argument, NULL, OPT_MEDIATYPE }, 
		{ "grayscale", required_argument, NULL, OPT_COLORMODE }, 
		{ "duplexprint", required_argument, NULL, OPT_DUPLEXPRINT }, 
		{ "jobid", required_argument, NULL, OPT_JOBID }, 
		{ "uuid", required_argument, NULL, OPT_UUID }, 
		{ 0, 0, 0, 0 }, 
	};
	const char *p_ppd_name = getenv("PPD");
	uint8_t *xmlBuf = NULL;
	int xmlBufSize;
	int retSize;

	char *tmpBuf = NULL;

	char	uuid[UUID_LEN + 1];

	DEBUG_PRINT( "[tocanonij] start tocanonij\n" );

	/* init CNCL API */
	GETSETCONFIGURATIONCOMMAND = NULL;
	GETSENDDATAPWGRASTERCOMMAND = NULL;
	GETPRINTCOMMAND = NULL;
	GETSTRINGWITHTAGFROMFILE = NULL;
	GETSETPAGECONFIGUARTIONCOMMAND = NULL;
	MAKEBJLSETTIMEJOB = NULL;
	GetProtocol = NULL;
	ParseCapabilityResponsePrint_HostEnv=NULL;
	MakeCommand_StartJob3 = NULL;
	ParseCapabilityResponsePrint_DateTime = NULL;
	MakeCommand_SetJobConfiguration = NULL;

	/* Init Settings */
	memset( &Settings, 0x00, sizeof(CNCL_P_SETTINGS) );
	InitpSettings( &Settings );
	memset( uuid, '\0', sizeof(uuid) );

	while( (opt = getopt_long( argc, argv, "0:", long_opt, &opt_index )) != -1) {
		switch( opt ) {
			case OPT_VERSION:
				DEBUG_PRINT3( "[tocanonij] OPTION(%s):VALUE(%s)\n", long_opt[opt_index].name, optarg );
				break;
			case OPT_FILTERPATH:
				DEBUG_PRINT3( "[tocanonij] OPTION(%s):VALUE(%s)\n", long_opt[opt_index].name, optarg );
				snprintf( libPathBuf, CN_LIB_PATH_LEN, "%s%s", optarg, CN_CNCL_LIBNAME );
				break;
			case OPT_PAPERSIZE:
				DEBUG_PRINT3( "[tocanonij] OPTION(%s):VALUE(%s)\n", long_opt[opt_index].name, optarg );
				Settings.papersize = ConvertStrToID( optarg, papersizeTbl );
				if ( IsBorderless( optarg ) ){
					Settings.borderlessprint = CNCL_PSET_BORDERLESS_ON;
				}
				else {
					Settings.borderlessprint = CNCL_PSET_BORDERLESS_OFF;
				}
				break;
			case OPT_MEDIATYPE:
				DEBUG_PRINT3( "[tocanonij] OPTION(%s):VALUE(%s)\n", long_opt[opt_index].name, optarg );
				Settings.mediatype = ConvertStrToID( optarg, mediatypeTbl );
				DEBUG_PRINT2( "[tocanonij] media : %d\n", Settings.mediatype );
				break;
#if 0
			case OPT_BORDERLESSPRINT:
				DEBUG_PRINT3( "[tocanonij] OPTION(%s):VALUE(%s)\n", long_opt[opt_index].name, optarg );
				if ( IsBorderless( optarg ) ){
					Settings.borderlessprint = CNCL_PSET_BORDERLESS_ON;
				}
				else {
					Settings.borderlessprint = CNCL_PSET_BORDERLESS_OFF;
				}
				break;
#endif
			case OPT_COLORMODE:
				DEBUG_PRINT3( "[tocanonij] OPTION(%s):VALUE(%s)\n", long_opt[opt_index].name, optarg );
				Settings.colormode = ConvertStrToID( optarg, colormodeTbl );
				break;
			case OPT_DUPLEXPRINT:
				DEBUG_PRINT3( "[tocanonij] OPTION(%s):VALUE(%s)\n", long_opt[opt_index].name, optarg );
				//Settings.duplexprint = CNCL_PSET_DUPLEX_OFF;
				Settings.duplexprint = ConvertStrToID( optarg, duplexprintTbl);
				break;

			case OPT_UUID:
				strncpy( uuid, optarg, strlen(optarg) );
				break;
			case OPT_JOBID:
				if( strlen( uuid ) == 0 ){
					strncpy( uuid, optarg, strlen(optarg) );
				}
				break;

			case '?':
				fprintf( stderr, "Error: invalid option %c:\n", optopt);
				break;
			default:
				break;
		}
	}

	/* dlopen */
	/* Make progamname with path of execute progname. */
	//snprintf( libPathBuf, CN_LIB_PATH_LEN, "%s%s", GetExecProgPath(), CN_CNCL_LIBNAME );
	DEBUG_PRINT2( "[tocanonij] libPath : %s\n", libPathBuf );
	if ( access( libPathBuf, R_OK ) ){
		strncpy( libPathBuf, CN_CNCL_LIBNAME, CN_LIB_PATH_LEN );
	}
	DEBUG_PRINT2( "[tocanonij] libPath : %s\n", libPathBuf );


	libclss = dlopen( libPathBuf, RTLD_LAZY );
	if ( !libclss ) {
		fprintf( stderr, "Error in dlopen\n" );
		goto onErr1;
	}

	GETSETCONFIGURATIONCOMMAND = dlsym( libclss, "CNCL_GetSetConfigurationCommand" );
	if ( dlerror() != NULL ) {
		fprintf( stderr, "Error in CNCL_GetSetConfigurationCommand. API not Found.\n" );
		goto onErr2;
	}
	GETSENDDATAPWGRASTERCOMMAND = dlsym( libclss, "CNCL_GetSendDataPWGRasterCommand" );
	if ( dlerror() != NULL ) {
		fprintf( stderr, "Error in CNCL_GetSendDataPWGRasterCommand\n" );
		goto onErr2;
	}
	GETPRINTCOMMAND = dlsym( libclss, "CNCL_GetPrintCommand" );
	if ( dlerror() != NULL ) {
		fprintf( stderr, "Error in CNCL_GetPrintCommand\n" );
		goto onErr2;
	}
	GETSTRINGWITHTAGFROMFILE = dlsym( libclss, "CNCL_GetStringWithTagFromFile" );
	if ( dlerror() != NULL ) {
		fprintf( stderr, "Error in CNCL_GetStringWithTagFromFile\n" );
		goto onErr2;
	}
	GETSETPAGECONFIGUARTIONCOMMAND = dlsym( libclss, "CNCL_GetSetPageConfigurationCommand" );
	if ( dlerror() != NULL ) {
		fprintf( stderr, "Load Error in CNCL_GetSetPageConfigurationCommand\n" );
		goto onErr2;
	}
	MAKEBJLSETTIMEJOB = dlsym( libclss, "CNCL_MakeBJLSetTimeJob" );
	if ( dlerror() != NULL ) {
		fprintf( stderr, "Load Error in CNCL_MakeBJLSetTimeJob\n" );
		goto onErr2;
	}
	GetProtocol = dlsym( libclss, "CNCL_GetProtocol" );
	if ( dlerror() != NULL ) {
		fprintf( stderr, "Load Error in CNCL_MakeBJLSetTimeJob\n" );
		goto onErr2;
	}
	ParseCapabilityResponsePrint_HostEnv = dlsym( libclss, "CNCL_ParseCapabilityResponsePrint_HostEnv" );
	if ( dlerror() != NULL ) {
		fprintf( stderr, "Load Error in CNCL_ParseCapabilityResponsePrint_HostEnv\n" );
		goto onErr2;
	}
	MakeCommand_StartJob3 = dlsym( libclss, "CNCL_MakeCommand_StartJob3" );
	if ( dlerror() != NULL ) {
		fprintf( stderr, "Load Error in CNCL_MakeCommand_StartJob3\n" );
		goto onErr2;
	}
	ParseCapabilityResponsePrint_DateTime = dlsym( libclss, "CNCL_ParseCapabilityResponsePrint_DateTime" );
	if ( dlerror() != NULL ) {
		fprintf( stderr, "Load Error in CNCL_ParseCapabilityResponsePrint_DateTime\n" );
		goto onErr2;
	}
	MakeCommand_SetJobConfiguration = dlsym( libclss, "CNCL_MakeCommand_SetJobConfiguration" );
	if ( dlerror() != NULL ) {
		fprintf( stderr, "Load Error in CNCL_MakeCommand_SetJobConfiguration\n" );
		goto onErr2;
	}

	/* Check Settings */
	if ( CheckSettings( &Settings ) != 0 ) goto onErr2;

#if 1
	/* Dump Settings */
	DumpSettings( &Settings );
#endif

	// const char *p_ppd_name = getenv("PPD");
	CAPABILITY_DATA capability;
	memset(&capability, '\0', sizeof(CAPABILITY_DATA));

	if( ! GetCapabilityFromPPDFile(p_ppd_name, &capability) ){
		goto onErr3;
	}

	int prot = GetProtocol( (char *)capability.deviceID, capability.deviceIDLength );

	if( prot == 2 ){
		xmlBufSize = GETSTRINGWITHTAGFROMFILE( p_ppd_name, CNCL_FILE_TAG_CAPABILITY, (int *)CNCL_DECODE_EXEC, &xmlBuf );

		unsigned short hostEnv = 0;
		hostEnv = ParseCapabilityResponsePrint_HostEnv( xmlBuf, xmlBufSize );

		/* Set JobID */
		strncpy( jobID, CN_START_JOBID2, sizeof(CN_START_JOBID2) );

		/* Allocate Buffer */
		bufSize = sizeof(char) * CN_BUFSIZE;

		if ( (bufTop = malloc( bufSize )) == NULL ) goto onErr2;

		/* Write StartJob Command */
		int ret = 0;
		ret = MakeCommand_StartJob3( hostEnv, uuid, jobID, bufTop, bufSize, &writtenSize );

		if ( ret != 0 ) {
			fprintf( stderr, "Error in CNCL_GetPrintCommand\n" );
			goto onErr2;
		}

		/* WriteData */
		if ( (retSize = write( 1, bufTop, writtenSize )) != writtenSize ) goto onErr2;


		char dateTime[15];
		memset(dateTime, '\0', sizeof(dateTime));

		ret = ParseCapabilityResponsePrint_DateTime( xmlBuf, xmlBufSize );

		if( ret == 2 ){
			time_t timer = time(NULL);
			struct tm *date = localtime(&timer);

			sprintf(dateTime, "%d%02d%02d%02d%02d%02d",
				date->tm_year+1900, date->tm_mon+1, date->tm_mday,
				date->tm_hour, date->tm_min, date->tm_sec);

			if ( (tmpBuf = malloc( bufSize )) == NULL ) goto onErr2;

			ret = MakeCommand_SetJobConfiguration( jobID, dateTime, tmpBuf, bufSize, &writtenSize );

			/* WriteData */
			if ( (retSize = write( 1, tmpBuf, writtenSize )) != writtenSize ) goto onErr2;

			// writtenSize += tmpWrittenSize;
		}
	}
	else{
		/* Set JobID */
		strncpy( jobID, CN_START_JOBID, sizeof(CN_START_JOBID) );

		/* OutputSetTime */
		if ( OutputSetTime( 1, jobID ) != 0 ) goto onErr2;


		/* Allocate Buffer */
		bufSize = sizeof(char) * CN_BUFSIZE;
		if ( (bufTop = malloc( bufSize )) == NULL ) goto onErr2;

		/* Write StartJob Command */
		if ( GETPRINTCOMMAND( bufTop, bufSize, &writtenSize_long, jobID, CNCL_COMMAND_START1 ) != 0 ) {
			fprintf( stderr, "Error in CNCL_GetPrintCommand\n" );
			goto onErr2;

		}

		/* WriteData */
		if ( (retSize = write( 1, bufTop, writtenSize_long )) != writtenSize_long ) goto onErr2;
	}

	/* Write SetConfiguration Command */
	if ( (xmlBufSize = GETSTRINGWITHTAGFROMFILE( p_ppd_name, CNCL_FILE_TAG_CAPABILITY, (int*)CNCL_DECODE_EXEC, &xmlBuf )) < 0 ){
		DEBUG_PRINT2( "[tocanonij] p_ppd_name : %s\n", p_ppd_name );
		DEBUG_PRINT2( "[tocanonij] xmlBufSize : %d\n", xmlBufSize );
		fprintf( stderr, "Error in CNCL_GetStringWithTagFromFile\n" );
		goto onErr3;
	}

	if ( GETSETCONFIGURATIONCOMMAND( &Settings, jobID, bufSize, (void *)xmlBuf, xmlBufSize, bufTop, &writtenSize_long ) != 0 ){
		fprintf( stderr, "Error in CNCL_GetSetConfigurationCommand\n" );
		goto onErr3;
	}
	/* WriteData */
	retSize = write( 1, bufTop, writtenSize_long );

	/* Write Page Data */
	while ( 1 ) {
		int readBytes = 0;
		int writeBytes;
		char *pCurrent;
		CNDATA CNData;
		long readSize = 0;
		unsigned short next_page;

		memset( &CNData, 0, sizeof(CNDATA) );

		/* read magic number */
		readBytes = read( fd, &CNData, sizeof(CNDATA) );
		if ( readBytes > 0 ){
			if ( CNData.magic_num != MAGIC_NUMBER_FOR_CNIJPWG ){
				fprintf( stderr, "Error illeagal MagicNumber\n" );
				goto onErr3;
			}
			if ( CNData.image_size < 0 ){
				fprintf( stderr, "Error illeagal dataSize\n" );
				goto onErr3;
			}
		}
		else if ( readBytes < 0 ){
			if ( errno == EINTR ) continue;
			fprintf( stderr, "DEBUG:[tocanonij] tocnij read error, %d\n", errno );
			goto onErr3;
		}
		else {
			DEBUG_PRINT( "DEBUG:[tocanonij] !!!DATA END!!!\n" );
			break; /* data end */
		}

		/* Write Next Page Info */
		if ( CNData.next_page ) {
			next_page = CNCL_PSET_NEXTPAGE_ON;
		}
		else {
			next_page = CNCL_PSET_NEXTPAGE_OFF;
		}
		if ( GETSETPAGECONFIGUARTIONCOMMAND( jobID, next_page, bufTop, bufSize, &writtenSize_long ) != 0 ) {
			fprintf( stderr, "Error in CNCL_GetPrintCommand\n" );
			goto onErr3;
		}
		/* WriteData */
		if ( (retSize = write( 1, bufTop, writtenSize_long )) != writtenSize_long ) goto onErr3;

		/* Write SendData Command */
		memset(	bufTop, 0x00, bufSize );
		readSize = CNData.image_size;
		if ( GETSENDDATAPWGRASTERCOMMAND( jobID, readSize, bufSize, bufTop, &writtenSize_long ) != 0 ) {
			DEBUG_PRINT( "Error in CNCL_GetSendDataJPEGCommand\n" );
			goto onErr3;
		}
		/* WriteData */
		retSize = write( 1, bufTop, writtenSize_long );

		while( readSize ){
			pCurrent = bufTop;

			if ( readSize - bufSize > 0 ){
				readBytes = read( fd, bufTop, bufSize );
				DEBUG_PRINT2( "[tocanonij] PASS tocanonij READ1<%d>\n", readBytes );
				if ( readBytes < 0 ) {
					if ( errno == EINTR ) continue;
				}
				readSize -= readBytes;
			}
			else {
				readBytes = read( fd, bufTop, readSize );
				DEBUG_PRINT2( "[tocanonij] PASS tocanonij READ2<%d>\n", readBytes );
				if ( readBytes < 0 ) {
					if ( errno == EINTR ) continue;
				}
				readSize -= readBytes;
			}

			do {
				writeBytes = write( 1, pCurrent, readBytes );
				DEBUG_PRINT2( "[tocanonij] PASS tocanonij WRITE<%d>\n", writeBytes );
				if( writeBytes < 0){
					if ( errno == EINTR ) continue;
					goto onErr3;
				}
				readBytes -= writeBytes;
				pCurrent += writeBytes;
			} while( writeBytes > 0 );

		}
	}

	/* CNCL_GetPrintCommand */
	if ( GETPRINTCOMMAND( bufTop, bufSize, &writtenSize_long, jobID, CNCL_COMMAND_END ) != 0 ) {
		DEBUG_PRINT( "Error in CNCL_GetPrintCommand\n" );
		goto onErr3;

	}
	/* WriteData */
	retSize = write( 1, bufTop, writtenSize_long );
	DEBUG_PRINT( "[tocanonij] to_cnijf <end>\n" );

	result = 0;
onErr3:
	if ( xmlBuf != NULL ){
		free( xmlBuf );
	}

onErr2:
	if ( bufTop != NULL ){
		free( bufTop );
	}

onErr1:
	if ( libclss != NULL ) {
		dlclose( libclss );
	}

	if( tmpBuf != NULL ){
		free(tmpBuf);
	}
	return result;
}
Exemplo n.º 2
0
		void
		dprintf_oterr(
			EndpointRef	ep,
			char		*message,
			NMErr	err,
			char		*file,
			NMSInt32	line)
		{
		char	*name;
		char	error[256];
		char	state[256];

			if (err)
			{
				switch (err)
				{
					PRINT_CASE(kOTOutOfMemoryErr);
					PRINT_CASE(kOTNotFoundErr);
					PRINT_CASE(kOTDuplicateFoundErr);
					PRINT_CASE(kOTBadAddressErr);
					PRINT_CASE(kOTBadOptionErr);
					PRINT_CASE(kOTAccessErr);
					PRINT_CASE(kOTBadReferenceErr);
					PRINT_CASE(kOTNoAddressErr);
					PRINT_CASE(kOTOutStateErr);
					PRINT_CASE(kOTBadSequenceErr);
					PRINT_CASE(kOTSysErrorErr);
					PRINT_CASE(kOTLookErr);
					PRINT_CASE(kOTBadDataErr);
					PRINT_CASE(kOTBufferOverflowErr);
					PRINT_CASE(kOTFlowErr);
					PRINT_CASE(kOTNoDataErr);
					PRINT_CASE(kOTNoDisconnectErr);
					PRINT_CASE(kOTNoUDErrErr);
					PRINT_CASE(kOTBadFlagErr);
					PRINT_CASE(kOTNoReleaseErr);
					PRINT_CASE(kOTNotSupportedErr);
					PRINT_CASE(kOTStateChangeErr);
					PRINT_CASE(kOTNoStructureTypeErr);
					PRINT_CASE(kOTBadNameErr);
					PRINT_CASE(kOTBadQLenErr);
					PRINT_CASE(kOTAddressBusyErr);
					PRINT_CASE(kOTIndOutErr);
					PRINT_CASE(kOTProviderMismatchErr);
					PRINT_CASE(kOTResQLenErr);
					PRINT_CASE(kOTResAddressErr);
					PRINT_CASE(kOTQFullErr);
					PRINT_CASE(kOTProtocolErr);
					PRINT_CASE(kOTBadSyncErr);
					PRINT_CASE(kOTCanceledErr);
					PRINT_CASE(kEPERMErr);
			//		PRINT_CASE(kENOENTErr);
					PRINT_CASE(kENORSRCErr);
					PRINT_CASE(kEINTRErr);
					PRINT_CASE(kEIOErr);
					PRINT_CASE(kENXIOErr);
					PRINT_CASE(kEBADFErr);
					PRINT_CASE(kEAGAINErr);
			//		PRINT_CASE(kENOMEMErr);
					PRINT_CASE(kEACCESErr);
					PRINT_CASE(kEFAULTErr);
					PRINT_CASE(kEBUSYErr);
			//		PRINT_CASE(kEEXISTErr);
					PRINT_CASE(kENODEVErr);
					PRINT_CASE(kEINVALErr);
					PRINT_CASE(kENOTTYErr);
					PRINT_CASE(kEPIPEErr);
					PRINT_CASE(kERANGEErr);
					PRINT_CASE(kEWOULDBLOCKErr);
			//		PRINT_CASE(kEDEADLKErr);
					PRINT_CASE(kEALREADYErr);
					PRINT_CASE(kENOTSOCKErr);
					PRINT_CASE(kEDESTADDRREQErr);
					PRINT_CASE(kEMSGSIZEErr);
					PRINT_CASE(kEPROTOTYPEErr);
					PRINT_CASE(kENOPROTOOPTErr);
					PRINT_CASE(kEPROTONOSUPPORTErr);
					PRINT_CASE(kESOCKTNOSUPPORTErr);
					PRINT_CASE(kEOPNOTSUPPErr);
					PRINT_CASE(kEADDRINUSEErr);
					PRINT_CASE(kEADDRNOTAVAILErr);
					PRINT_CASE(kENETDOWNErr);
					PRINT_CASE(kENETUNREACHErr);
					PRINT_CASE(kENETRESETErr);
					PRINT_CASE(kECONNABORTEDErr);
					PRINT_CASE(kECONNRESETErr);
					PRINT_CASE(kENOBUFSErr);
					PRINT_CASE(kEISCONNErr);
					PRINT_CASE(kENOTCONNErr);
					PRINT_CASE(kESHUTDOWNErr);
					PRINT_CASE(kETOOMANYREFSErr);
					PRINT_CASE(kETIMEDOUTErr);
					PRINT_CASE(kECONNREFUSEDErr);
					PRINT_CASE(kEHOSTDOWNErr);
					PRINT_CASE(kEHOSTUNREACHErr);
					PRINT_CASE(kEPROTOErr);
					PRINT_CASE(kETIMEErr);
					PRINT_CASE(kENOSRErr);
					PRINT_CASE(kEBADMSGErr);
					PRINT_CASE(kECANCELErr);
					PRINT_CASE(kENOSTRErr);
					PRINT_CASE(kENODATAErr);
					PRINT_CASE(kEINPROGRESSErr);
					PRINT_CASE(kESRCHErr);
					PRINT_CASE(kENOMSGErr);
					PRINT_CASE(kOTClientNotInittedErr);
					PRINT_CASE(kOTPortHasDiedErr);
					PRINT_CASE(kOTPortWasEjectedErr);
					PRINT_CASE(kOTBadConfigurationErr);
					PRINT_CASE(kOTConfigurationChangedErr);
					PRINT_CASE(kOTUserRequestedErr);
					PRINT_CASE(kOTPortLostConnection);

					default:
						name = "< unknown >";
						break;
				}
				strcpy(error,name);
				
				if (ep)
				{
					switch (OTGetEndpointState(ep))
					{	
						PRINT_CASE(T_UNINIT);
						PRINT_CASE(T_UNBND);
						PRINT_CASE(T_IDLE);
						PRINT_CASE(T_OUTCON);
						PRINT_CASE(T_INCON);
						PRINT_CASE(T_DATAXFER);
						PRINT_CASE(T_OUTREL);
						PRINT_CASE(T_INREL);

						default:
							name = "< unknown >";
							break;
					}
				}
				else
					name = "<unknown>";

				strcpy(state,name);
					
				DEBUG_PRINT("EP: %p (state: %s), OTError for %s: %s (%d). File: %s, %d",ep, state, message, error, err, file, line);
			}
		}
Exemplo n.º 3
0
	NMErr
	dprintf_err(
		char	*message,
		NMErr	err,
		char		*file,
		NMSInt32	line)
	{
	char 	*name;
		
		if (err != -1)
		{
			DEBUG_PRINT("error value %d passed to dprintf_sockerr for %s. not checking errno. %s line %d",err,message,file,line);
			return 0;
		}
			
		switch (errno)
		{
			PRINT_CASE(EPERM);
			PRINT_CASE(ENOENT);
			PRINT_CASE(ESRCH);
			PRINT_CASE(EINTR);
			PRINT_CASE(EIO);
			PRINT_CASE(ENXIO);
			PRINT_CASE(E2BIG);
			PRINT_CASE(ENOEXEC);
			PRINT_CASE(EBADF);
			PRINT_CASE(ECHILD);
			PRINT_CASE(EDEADLK);
			PRINT_CASE(ENOMEM);
			PRINT_CASE(EACCES);
			PRINT_CASE(EFAULT);
			PRINT_CASE(ENOTBLK);
			PRINT_CASE(EBUSY);
			PRINT_CASE(EEXIST);
			PRINT_CASE(EXDEV);
			PRINT_CASE(ENODEV);
			PRINT_CASE(ENOTDIR);
			PRINT_CASE(EISDIR);
			PRINT_CASE(EINVAL);
			PRINT_CASE(ENFILE);
			PRINT_CASE(EMFILE);
			PRINT_CASE(ENOTTY);
			PRINT_CASE(ETXTBSY);
			PRINT_CASE(EFBIG);
			PRINT_CASE(ENOSPC);
			PRINT_CASE(ESPIPE);
			PRINT_CASE(EROFS);
			PRINT_CASE(EMLINK);
			PRINT_CASE(EPIPE);
			PRINT_CASE(EDOM);
			PRINT_CASE(ERANGE);
			PRINT_CASE(EWOULDBLOCK);
			PRINT_CASE(EINPROGRESS);
			PRINT_CASE(EALREADY);
			PRINT_CASE(ENOTSOCK);
			PRINT_CASE(EDESTADDRREQ);
			PRINT_CASE(EMSGSIZE);
			PRINT_CASE(EPROTOTYPE);
			PRINT_CASE(ENOPROTOOPT);
			PRINT_CASE(EPROTONOSUPPORT);
			PRINT_CASE(ESOCKTNOSUPPORT);
			PRINT_CASE(ENOTSUP);
			PRINT_CASE(EPFNOSUPPORT);
			PRINT_CASE(EAFNOSUPPORT);
			PRINT_CASE(EADDRINUSE);
			PRINT_CASE(EADDRNOTAVAIL);
			PRINT_CASE(ENETDOWN);
			PRINT_CASE(ENETUNREACH);
			PRINT_CASE(ENETRESET);
			PRINT_CASE(ECONNABORTED);
			PRINT_CASE(ECONNRESET);
			PRINT_CASE(ENOBUFS);
			PRINT_CASE(EISCONN);
			PRINT_CASE(ENOTCONN);
			PRINT_CASE(ESHUTDOWN);
			PRINT_CASE(ETOOMANYREFS);
			PRINT_CASE(ETIMEDOUT);
			PRINT_CASE(ECONNREFUSED);
			PRINT_CASE(ELOOP);
			PRINT_CASE(ENAMETOOLONG);
			PRINT_CASE(EHOSTDOWN);
			PRINT_CASE(EHOSTUNREACH);
			PRINT_CASE(ENOTEMPTY);
			PRINT_CASE(EUSERS);
			PRINT_CASE(EDQUOT);
			PRINT_CASE(ESTALE);
			PRINT_CASE(EREMOTE);
			PRINT_CASE(ENOLCK);
			PRINT_CASE(ENOSYS);
			PRINT_CASE(EOVERFLOW);
#if (OP_PLATFORM_MAC_MACHO)
				PRINT_CASE(EPROCLIM);
				PRINT_CASE(EBADRPC);
				PRINT_CASE(ERPCMISMATCH);
				PRINT_CASE(EPROGUNAVAIL);
				PRINT_CASE(EFTYPE);
				PRINT_CASE(ENEEDAUTH);
				PRINT_CASE(EPWROFF);
				PRINT_CASE(EDEVERR);
				PRINT_CASE(EBADEXEC);
				PRINT_CASE(EBADARCH);
				PRINT_CASE(ESHLIBVERS);
				PRINT_CASE(EBADMACHO);
				PRINT_CASE(EAUTH);
			#endif
			
			default:
				name = "<unknown>";
				break;
		}

		DEBUG_PRINT("Socket Err: %s - %s (%d) File: %s, %d", message, name, errno,file, line);
		return err;
	}
Exemplo n.º 4
0
// -----------------------------------------------------------------------------
// CExprUDPMsg::TryParsingL
// -----------------------------------------------------------------------------
//
TInt CExprUDPMsg::TryParsingL( TDes8& aData, TInt& aLength )
    {
    __ASSERT_ALWAYS( aData.Left( KUDPPrefix().Length() ) == KUDPPrefix,
        User::Panic( _L("Protocol"), 1 ) );

    // UDP:0123,000e,[Some test data]
    TInt frameOverhead =
        KUDPPrefix().Length() +
        KHexDecimalLength +
        KPortSuffix().Length() +
        KHexDecimalLength +
        KLengthSuffix().Length() +
        KDataSuffix().Length() +
        KMessageSuffix().Length();

    if ( aData.Length() >= frameOverhead )
        {
        TPtrC8 portPtr(
            aData.Mid( KUDPPrefix().Length(), KHexDecimalLength ) );

        TLex8 portLexer( portPtr );
        TUint port;
        if ( portLexer.Val( port, EHex ) != KErrNone )
            {
            return KErrCorrupt;
            }
        DEBUG_PRINT( DEBUG_STRING( "CExprUDPMsg::TryParsingL, port = %d" ), port );

        //Check port suffix
        if ( aData.Mid( KUDPPrefix().Length() +
            KHexDecimalLength, KPortSuffix().Length() ) != KPortSuffix )
            {
            return KErrCorrupt;
            }

        TPtrC8 lengthPtr( aData.Mid( KUDPPrefix().Length() +
            KHexDecimalLength + KPortSuffix().Length(), KHexDecimalLength ) );
        TLex8 lengthLexer( lengthPtr );
        TUint length;
        if ( lengthLexer.Val( length, EHex ) != KErrNone )
            {
            return KErrCorrupt;
            }
        DEBUG_PRINT( DEBUG_STRING( "CExprUDPMsg::TryParsingL, length = %d" ), length );

        //Check length suffix
        if ( aData.Mid(
            KUDPPrefix().Length() +
            KHexDecimalLength +
            KPortSuffix().Length() +
            KHexDecimalLength, KLengthSuffix().Length() ) != KLengthSuffix )
            {
            return KErrCorrupt;
            }

        DEBUG_PRINT( DEBUG_STRING( "CExprUDPMsg::TryParsingL, parsing data" ), length );

        if ( aData.Length() >= TInt( frameOverhead + length ) )
            {
            TInt messagePos = KUDPPrefix().Length() +
                KHexDecimalLength +
                KPortSuffix().Length() +
                KHexDecimalLength +
                KLengthSuffix().Length();

            TPtrC8 message( aData.Mid( messagePos, length ) );
            if ( aData.Mid( messagePos + length,
                KDataSuffix().Length() ) != KDataSuffix )
                {
                return KErrCorrupt;
                }
            DEBUG_PRINT( DEBUG_STRING( "CExprUDPMsg::TryParsingL, message OK" ) );

            if ( aData.Mid( messagePos + length + KDataSuffix().Length(),
                KMessageSuffix().Length() ) != KMessageSuffix )
                {
                return KErrCorrupt;
                }

            // send parsed results
            iObserver->FrameParsedL( port, message );
            // set the length of the handled message
            aLength = frameOverhead + length;

            return KErrNone;
            }

        }
    return KErrNone;
    }
Exemplo n.º 5
0
void printPMTList(void)
{
    PmtTable*    psTempPmt;
    ProgElement* psTempElement;
    int iDescCounter,iElemStreamIdx;

    psTempPmt = m_psPmtList;
    while(psTempPmt)
    {
        DEBUG_PRINT("ProgNumber      = %d\n",psTempPmt->iProgNumber);
        DEBUG_PRINT("VersionNumber   = %d\n",psTempPmt->iVersionNumber);
        DEBUG_PRINT("ValidPmt        = %d\n",psTempPmt->bValidPmt);
        DEBUG_PRINT("PcrPid          = 0x%04X\n",psTempPmt->iPcrPid);
        if (psTempPmt->iOuterDescLength > 0)
        {
            DEBUG_PRINT("OuterDescLength = %d\n",psTempPmt->iOuterDescLength);
            DEBUG_PRINT("Outer Private Descriptor:\n");
            for (iDescCounter=0; iDescCounter < psTempPmt->iOuterDescLength; iDescCounter++)
            {
                DEBUG_PRINT("0x%02X ",psTempPmt->pcOuterDesc[iDescCounter]&0xFF);
            }
        }
        DEBUG_PRINT("\n");

        psTempElement = psTempPmt->psElementList;
        iElemStreamIdx = 0;
	while (psTempElement)
        {
            DEBUG_PRINT("	StreamType       = 0x%02X\n",psTempElement->iStreamType);
            DEBUG_PRINT("	Pid              = 0x%04X\n",psTempElement->iPid);
            if (psTempElement->iProgElDescLength > 0)
            {
                DescAttr sDescAttr;
                iDescCounter=0;

                {
                    int j;
                    DEBUG_PRINT("	Raw Descriptor\n");
		    DEBUG_PRINT("	");
                    for (j = 0; j < psTempElement->iProgElDescLength; j++)
                    {
                        DEBUG_PRINT("0x%02X ",psTempElement->pcProgElDesc[j]&0xFF);
                    }
                    DEBUG_PRINT("\n");
                }

                sDescAttr.eParam = PMT_PRIVATE_DESCRIPTOR_TAG;
                while (getElementaryPrivateDescPayload(psTempPmt,iElemStreamIdx,iDescCounter,&sDescAttr) == PMT_OK)
                {
                    DEBUG_PRINT("	Tag 0x%02X, ",sDescAttr.uAttr.iDescTag&0xFF);
                    DEBUG_PRINT("%s\n",getDescTypeString(sDescAttr.uAttr.iDescTag));
                    memset(&sDescAttr,0,sizeof(DescAttr));
                    sDescAttr.eParam = PMT_PRIVATE_DESCRIPTOR_PAYLOAD;
                    if (getElementaryPrivateDescPayload(psTempPmt,iElemStreamIdx,iDescCounter,&sDescAttr) == PMT_OK)
                    {
                        int i;
                        DEBUG_PRINT("	Descriptor Payload Length %d\n",sDescAttr.uAttr.sPayload.iPayloadLength);
			DEBUG_PRINT("	");
                        for (i=0; i < sDescAttr.uAttr.sPayload.iPayloadLength; i++)
                        {
                            DEBUG_PRINT("0x%02X ",sDescAttr.uAttr.sPayload.pcPayload[i]&0xFF);
                        }
                        DEBUG_PRINT("\n");
                    }
                    iDescCounter += 1;
                    memset(&sDescAttr,0,sizeof(DescAttr));
                    sDescAttr.eParam = PMT_PRIVATE_DESCRIPTOR_TAG;
                }
            }
            DEBUG_PRINT("\n");
            psTempElement = psTempElement->psNext;
            iElemStreamIdx += 1;
        }
        DEBUG_PRINT("\n");
        psTempPmt = psTempPmt->psNext;
    }    
}
Exemplo n.º 6
0
/*
 * Device open
 */
SYSCALL ID tk_opn_dev_impl( UB *devnm, UINT omode )
{
	OPNFN	openfn;
	VP	exinf;
#if TA_GP
	VP	gp;
#endif
	UB	pdevnm[L_DEVNM + 1];
	INT	unitno;
	ResCB	*rescb;
	DevCB	*devcb;
	OpnCB	*opncb;
	ER	ercd;
	ID	semid;

	unitno = knl_phydevnm(pdevnm, devnm);

	/* Get resource management information */
	rescb = knl_GetResCB();
	if ( rescb == NULL ) {
		ercd = E_CTX;
		goto err_ret1;
	}

	LockDM();

	/* Search device to open */
	devcb = knl_searchDevCB(pdevnm);
	if ( devcb == NULL || unitno > devcb->ddev.nsub ) {
		ercd = E_NOEXS;
		goto err_ret2;
	}

	/* Check open mode */
	ercd = chkopenmode(devcb, unitno, omode);
	if ( ercd < E_OK ) {
		goto err_ret2;
	}

	openfn = (OPNFN)devcb->ddev.openfn;
	exinf = devcb->ddev.exinf;
#if TA_GP
	gp = devcb->ddev.gp;
#endif

	/* Is device driver call required? */
	if ( knl_chkopen(devcb, unitno) && (devcb->ddev.drvatr & TDA_OPENREQ) == 0 ) {
		openfn = NULL;
	}

	/* Get open management block */
	opncb = newOpnCB(devcb, unitno, omode, rescb);
	if ( opncb == NULL ) {
		ercd = E_LIMIT;
		goto err_ret2;
	}

	semid = tk_cre_sem_impl(&knl_pk_csem_DM);
	if ( semid < E_OK ) {
		ercd = E_SYS;
		goto err_ret2_5;
	}
	opncb->abort_semid = semid;

	UnlockDM();

	if ( openfn != NULL ) {
		/* Device driver call */
		DISABLE_INTERRUPT;
		knl_ctxtsk->sysmode++;
		ENABLE_INTERRUPT;
#if TA_GP
		ercd = CallDeviceDriver(DEVID(devcb, unitno), omode, exinf, 0,
								(FP)openfn, gp);
#else
		ercd = (*openfn)(DEVID(devcb, unitno), omode, exinf);
#endif
		DISABLE_INTERRUPT;
		knl_ctxtsk->sysmode--;
		ENABLE_INTERRUPT;

		if ( ercd < E_OK ) {
			goto err_ret3;
		}
	}

	LockDM();
	opncb->resid = 1; /* Indicate that open processing is completed */
	UnlockDM();

	return DD(opncb);

err_ret3:
	LockDM();
err_ret2_5:
	knl_delOpnCB(opncb, TRUE);
err_ret2:
	UnlockDM();
err_ret1:
	DEBUG_PRINT(("tk_opn_dev_impl ercd = %d\n", ercd));
	return ercd;
}
Exemplo n.º 7
0
/*
 * Request for starting input/output to device
 */
EXPORT ID knl_request( ID dd, W start, VP buf, W size, TMO tmout, INT cmd )
{
	EXCFN	execfn;
	VP	exinf;
#if TA_GP
	VP	gp;
#endif
	OpnCB	*opncb;
	DevCB	*devcb;
	ReqCB	*reqcb;
	UINT	m;
	ER	ercd;

	LockDM();

	if ( start <= -0x00010000 && start >= -0x7fffffff ) {
		m = 0; /* Ignore open mode */
	} else {
		m = ( cmd == TDC_READ )? TD_READ: TD_WRITE;
	}
	ercd = knl_check_devdesc(dd, m, &opncb);
	if ( ercd < E_OK ) {
		goto err_ret1;
	}

	devcb = opncb->devcb;
	execfn = (EXCFN)devcb->ddev.execfn;
	exinf = devcb->ddev.exinf;
#if TA_GP
	gp = devcb->ddev.gp;
#endif

	/* Get request management block */
	reqcb = newReqCB(opncb);
	if ( reqcb == NULL ) {
		ercd = E_LIMIT;
		goto err_ret1;
	}

	/* Set request packet */
	reqcb->req.next   = NULL;
	reqcb->req.exinf  = NULL;
	reqcb->req.devid  = DEVID(devcb, opncb->unitno);
	reqcb->req.cmd    = cmd;
	reqcb->req.abort  = FALSE;
	reqcb->req.start  = start;
	reqcb->req.size   = size;
	reqcb->req.buf    = buf;
	reqcb->req.asize  = 0;
	reqcb->req.error  = 0;

	/* Indicate that it is during processing */
	reqcb->tskid = tk_get_tid_impl();

	UnlockDM();

	/* Device driver call */
	DISABLE_INTERRUPT;
	knl_ctxtsk->sysmode++;
	ENABLE_INTERRUPT;
#if TA_GP
	ercd = CallDeviceDriver(&reqcb->req, tmout, exinf, 0, (FP)execfn, gp);
#else
	ercd = (*execfn)(&reqcb->req, tmout, exinf);
#endif
	DISABLE_INTERRUPT;
	knl_ctxtsk->sysmode--;
	ENABLE_INTERRUPT;

	LockDM();

	/* Indicate that it is not during processing */
	reqcb->tskid = 0;

	/* If there is an abort completion wait task,
	   notify abort completion */
	if ( opncb->abort_tskid > 0 && --opncb->abort_cnt == 0 ) {
		tk_sig_sem_impl(opncb->abort_semid, 1);
	}

	if ( ercd < E_OK ) {
		goto err_ret2;
	}

	UnlockDM();

	return REQID(reqcb);

err_ret2:
	knl_delReqCB(reqcb);
err_ret1:
	UnlockDM();
	DEBUG_PRINT(("knl_request ercd = %d\n", ercd));
	return ercd;
}
Exemplo n.º 8
0
void MRAILI_Release_vbuf(vbuf* v)
{
#ifdef _ENABLE_UD_
    /* This message might be in progress. Wait for ib send completion 
     * to release this buffer to avoid to reusing buffer
     */
    if(v->transport== IB_TRANSPORT_UD 
        && v->flags & UD_VBUF_SEND_INPROGRESS) {
        v->flags |= UD_VBUF_FREE_PENIDING;
        return;
    }
#endif

    /* note this correctly handles appending to empty free list */
#if !defined(CKPT)
    if (MPIDI_CH3I_RDMA_Process.has_srq
#if defined(RDMA_CM)
        || MPIDI_CH3I_RDMA_Process.use_rdma_cm_on_demand
#endif /* defined(RDMA_CM) */
        || MPIDI_CH3I_Process.cm_type == MPIDI_CH3I_CM_ON_DEMAND)
#endif /* !defined(CKPT) */
    {
        pthread_spin_lock(&vbuf_lock);
    }

    DEBUG_PRINT("release_vbuf: releasing %p previous head = %p, padding %d\n", v, free_vbuf_head, v->padding);

#ifdef _ENABLE_UD_
    if(v->transport == IB_TRANSPORT_UD) {
        MPIU_Assert(v != ud_free_vbuf_head);
        v->desc.next = ud_free_vbuf_head;
        ud_free_vbuf_head = v;
        ++ud_num_free_vbuf;
        ++ud_num_vbuf_freed;
    } 
    else 
#endif /* _ENABLE_UD_ */
    {
        MPIU_Assert(v != free_vbuf_head);
        v->desc.next = free_vbuf_head;
        free_vbuf_head = v;
        ++num_free_vbuf;
        ++num_vbuf_freed;
    }

    if (v->padding != NORMAL_VBUF_FLAG
        && v->padding != RPUT_VBUF_FLAG
        && v->padding != RGET_VBUF_FLAG
        && v->padding != RDMA_ONE_SIDED)
    {
        ibv_error_abort(GEN_EXIT_ERR, "vbuf not correct.\n");
    }

    *v->head_flag = 0;
    v->pheader = NULL;
    v->content_size = 0;
    v->sreq = NULL;
    v->vc = NULL;

#if !defined(CKPT)
    if (MPIDI_CH3I_RDMA_Process.has_srq
#if defined(RDMA_CM)
        || MPIDI_CH3I_RDMA_Process.use_rdma_cm_on_demand
#endif /* defined(RDMA_CM) */
        || MPIDI_CH3I_Process.cm_type == MPIDI_CH3I_CM_ON_DEMAND)
#endif /* !defined(CKPT) */
    {
        pthread_spin_unlock(&vbuf_lock);
    }
}
static void sensorsDeviceInit(void)
{
  isMagnetometerPresent = false;
  isBarometerPresent = false;

  // Wait for sensors to startup
  while (xTaskGetTickCount() < 1000);

  i2cdevInit(I2C3_DEV);
  mpu6500Init(I2C3_DEV);
  if (mpu6500TestConnection() == true)
  {
    DEBUG_PRINT("MPU9250 I2C connection [OK].\n");
  }
  else
  {
    DEBUG_PRINT("MPU9250 I2C connection [FAIL].\n");
  }

  mpu6500Reset();
  vTaskDelay(M2T(50));
  // Activate MPU6500
  mpu6500SetSleepEnabled(false);
  // Delay until registers are reset
  vTaskDelay(M2T(100));
  // Set x-axis gyro as clock source
  mpu6500SetClockSource(MPU6500_CLOCK_PLL_XGYRO);
  // Delay until clock is set and stable
  vTaskDelay(M2T(200));
  // Enable temp sensor
  mpu6500SetTempSensorEnabled(true);
  // Disable interrupts
  mpu6500SetIntEnabled(false);
  // Connect the MAG and BARO to the main I2C bus
  mpu6500SetI2CBypassEnabled(true);
  // Set gyro full scale range
  mpu6500SetFullScaleGyroRange(SENSORS_GYRO_FS_CFG);
  // Set accelerometer full scale range
  mpu6500SetFullScaleAccelRange(SENSORS_ACCEL_FS_CFG);
  // Set accelerometer digital low-pass bandwidth
  mpu6500SetAccelDLPF(MPU6500_ACCEL_DLPF_BW_41);

#if SENSORS_MPU6500_DLPF_256HZ
  // 256Hz digital low-pass filter only works with little vibrations
  // Set output rate (15): 8000 / (1 + 7) = 1000Hz
  mpu6500SetRate(7);
  // Set digital low-pass bandwidth
  mpu6500SetDLPFMode(MPU6500_DLPF_BW_256);
#else
  // To low DLPF bandwidth might cause instability and decrease agility
  // but it works well for handling vibrations and unbalanced propellers
  // Set output rate (1): 1000 / (1 + 0) = 1000Hz
  mpu6500SetRate(0);
  // Set digital low-pass bandwidth for gyro
  mpu6500SetDLPFMode(MPU6500_DLPF_BW_98);
  // Init second order filer for accelerometer
  for (uint8_t i = 0; i < 3; i++)
  {
    lpf2pInit(&gyroLpf[i], 1000, GYRO_LPF_CUTOFF_FREQ);
    lpf2pInit(&accLpf[i],  1000, ACCEL_LPF_CUTOFF_FREQ);
  }
#endif


#ifdef SENSORS_ENABLE_MAG_AK8963
  ak8963Init(I2C3_DEV);
  if (ak8963TestConnection() == true)
  {
    isMagnetometerPresent = true;
    ak8963SetMode(AK8963_MODE_16BIT | AK8963_MODE_CONT2); // 16bit 100Hz
    DEBUG_PRINT("AK8963 I2C connection [OK].\n");
  }
  else
  {
    DEBUG_PRINT("AK8963 I2C connection [FAIL].\n");
  }
#endif

#ifdef SENSORS_ENABLE_PRESSURE_LPS25H
  lps25hInit(I2C3_DEV);
  if (lps25hTestConnection() == true)
  {
    lps25hSetEnabled(true);
    isBarometerPresent = true;
    DEBUG_PRINT("LPS25H I2C connection [OK].\n");
  }
  else
  {
    //TODO: Should sensor test fail hard if no connection
    DEBUG_PRINT("LPS25H I2C connection [FAIL].\n");
  }
#endif

  cosPitch = cosf(configblockGetCalibPitch() * (float) M_PI/180);
  sinPitch = sinf(configblockGetCalibPitch() * (float) M_PI/180);
  cosRoll = cosf(configblockGetCalibRoll() * (float) M_PI/180);
  sinRoll = sinf(configblockGetCalibRoll() * (float) M_PI/180);
}
Exemplo n.º 10
0
/*
 *Return the difference between 2 timeval structs 
 * in microseconds
 */
static void perf_timer_exit(void)
{
	DEBUG_PRINT("Perf Timer:NOTIFY	:Exiting Performance timer");
}
Exemplo n.º 11
0
static int allocate_vbuf_region(int nvbufs)
{

    struct vbuf_region *reg = NULL;
    void *mem = NULL;
    int i = 0;
    vbuf *cur = NULL;
    void *vbuf_dma_buffer = NULL;
    int alignment_vbuf = 64;
    int alignment_dma = getpagesize();
    int result = 0;

    DEBUG_PRINT("Allocating a new vbuf region.\n");

    if (free_vbuf_head != NULL)
    {
        ibv_error_abort(GEN_ASSERT_ERR, "free_vbuf_head = NULL");
    }

    /* are we limiting vbuf allocation?  If so, make sure
     * we dont alloc more than allowed
     */
    if (rdma_vbuf_max > 0)
    {
        nvbufs = MIN(nvbufs, rdma_vbuf_max - vbuf_n_allocated);

        if (nvbufs <= 0)
        {
            ibv_error_abort(GEN_EXIT_ERR, "VBUF alloc failure, limit exceeded");
        }
    }

    reg = (struct vbuf_region *) MPIU_Malloc (sizeof(struct vbuf_region));

    if (NULL == reg)
    {
        ibv_error_abort(GEN_EXIT_ERR, "Unable to malloc a new struct vbuf_region");
    }

    if (rdma_enable_hugepage) {
        result = alloc_hugepage_region (&reg->shmid, &vbuf_dma_buffer, &nvbufs, rdma_vbuf_total_size);
    }

    /* do posix_memalign if enable hugepage disabled or failed */
    if (rdma_enable_hugepage == 0 || result != 0 )  
    {
        reg->shmid = -1;
        result = posix_memalign(&vbuf_dma_buffer, alignment_dma, nvbufs * rdma_vbuf_total_size);
    }

    if ((result!=0) || (NULL == vbuf_dma_buffer))
    {
       ibv_error_abort(GEN_EXIT_ERR, "unable to malloc vbufs DMA buffer");
    }
    
    if (posix_memalign(
        (void**) &mem,
        alignment_vbuf,
        nvbufs * sizeof(vbuf)))
    {
        fprintf(stderr, "[%s %d] Cannot allocate vbuf region\n", __FILE__, __LINE__);
        return -1;
    }
  
    /* region should be registered for all of the hca */
    for (i=0 ; i < rdma_num_hcas; ++i)
    {
        reg->mem_handle[i] = ibv_reg_mr(
            ptag_save[i],
            vbuf_dma_buffer,
            nvbufs * rdma_vbuf_total_size,
            IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_WRITE);

        if (!reg->mem_handle[i])
        {
            /* de-register already registered with other hcas*/
            for (i = i-1; i >=0 ; --i)
            {
                if (reg->mem_handle[i] != NULL
                        && ibv_dereg_mr(reg->mem_handle[i]))
                {
                    fprintf(stderr, "[%s %d] Cannot de-register vbuf region\n", __FILE__, __LINE__);
                }
            }
            /* free allocated buffers */
            free(vbuf_dma_buffer);
            free(mem);
            MPIU_Free(reg);
            fprintf(stderr, "[%s %d] Cannot register vbuf region\n", __FILE__, __LINE__);
            return -1;
        }
    }

    MPIU_Memset(mem, 0, nvbufs * sizeof(vbuf));
    MPIU_Memset(vbuf_dma_buffer, 0, nvbufs * rdma_vbuf_total_size);

    vbuf_n_allocated += nvbufs;
    num_free_vbuf += nvbufs;
    reg->malloc_start = mem;
    reg->malloc_buf_start = vbuf_dma_buffer;
    reg->malloc_end = (void *) ((char *) mem + nvbufs * sizeof(vbuf));
    reg->malloc_buf_end = (void *) ((char *) vbuf_dma_buffer + nvbufs * rdma_vbuf_total_size);

    reg->count = nvbufs;
    free_vbuf_head = mem;
    reg->vbuf_head = free_vbuf_head;

    DEBUG_PRINT(
        "VBUF REGION ALLOCATION SZ %d TOT %d FREE %ld NF %ld NG %ld\n",
        nvbufs,
        vbuf_n_allocated,
        num_free_vbuf,
        num_vbuf_freed,
        num_vbuf_get);

    /* init the free list */
    for (i = 0; i < nvbufs - 1; ++i)
    {
        cur = free_vbuf_head + i;
        cur->desc.next = free_vbuf_head + i + 1;
        cur->region = reg;
	cur->head_flag = (VBUF_FLAG_TYPE *) ((char *)vbuf_dma_buffer
            + (i + 1) * rdma_vbuf_total_size
            - sizeof * cur->head_flag);
        cur->buffer = (unsigned char *) ((char *)vbuf_dma_buffer
            + i * rdma_vbuf_total_size);

        cur->eager = 0;
        cur->content_size = 0;
        cur->coalesce = 0;
    }

    /* last one needs to be set to NULL */
    cur = free_vbuf_head + nvbufs - 1;
    cur->desc.next = NULL;
    cur->region = reg;
    cur->head_flag = (VBUF_FLAG_TYPE *) ((char *)vbuf_dma_buffer
        + nvbufs * rdma_vbuf_total_size
        - sizeof * cur->head_flag);
    cur->buffer = (unsigned char *) ((char *)vbuf_dma_buffer
        + (nvbufs - 1) * rdma_vbuf_total_size);
    cur->eager = 0;
    cur->content_size = 0;
    cur->coalesce = 0;

    /* thread region list */
    reg->next = vbuf_region_head;
    vbuf_region_head = reg;

    return 0;
}
Exemplo n.º 12
0
int MPIDI_CH3I_MRAILI_Cq_poll(vbuf **vbuf_handle, 
        MPIDI_VC_t * vc_req, int receiving, int is_blocking)
{
    int ne, ret;
    MPIDI_VC_t *vc = NULL;
    struct ibv_wc wc;
    vbuf *v;
    int i = 0;
    int cq_choice = 0;
    int num_cqs = 0;
    int needed;
    int is_send_completion;
    int type = T_CHANNEL_NO_ARRIVE;
    static unsigned long nspin = 0;
    struct ibv_cq *ev_cq; 
    struct ibv_cq *chosen_cq; 
    void *ev_ctx;
    MPIDI_CH3I_MRAILI_Pkt_comm_header *p;

    int myrank;
    MPIDI_STATE_DECL(MPID_GEN2_MRAILI_CQ_POLL);
    MPIDI_FUNC_ENTER(MPID_GEN2_MRAILI_CQ_POLL);
    myrank = PMI_Get_rank(&myrank);

    *vbuf_handle = NULL;
    needed = 0;

    if (!receiving && !vc_req) {
        type = MPIDI_CH3I_MRAILI_Test_pkt(vbuf_handle);
        if (type == T_CHANNEL_EXACT_ARRIVE 
                || type == T_CHANNEL_CONTROL_MSG_ARRIVE)
            goto fn_exit;
    }

    if (rdma_iwarp_use_multiple_cq &&
        MV2_IS_CHELSIO_IWARP_CARD(MPIDI_CH3I_RDMA_Process.hca_type) &&
        (MPIDI_CH3I_RDMA_Process.cluster_size != VERY_SMALL_CLUSTER)) {
        num_cqs = 2;
    } else {
        num_cqs = 1;
    }

    for (; i < rdma_num_hcas; ++i) {
        for (cq_choice = 0; cq_choice < num_cqs; ++cq_choice) {
            if (1 == num_cqs) {
	            chosen_cq = MPIDI_CH3I_RDMA_Process.cq_hndl[i];
	        } else {
	            if (0 == cq_choice) {
	                chosen_cq = MPIDI_CH3I_RDMA_Process.send_cq_hndl[i];
                } else {
	                chosen_cq = MPIDI_CH3I_RDMA_Process.recv_cq_hndl[i];
                }
	        }
	        ne = ibv_poll_cq(chosen_cq, 1, &wc);
	        if (ne < 0 ) {
	            ibv_error_abort(IBV_RETURN_ERR, "Fail to poll cq\n");
	        } else if (ne) {         
	            v = (vbuf *) ((uintptr_t) wc.wr_id);
	
	            vc = (MPIDI_VC_t *) (v->vc);
                cq_poll_completion = 1;
	
	            if (wc.status != IBV_WC_SUCCESS) {
	                if (wc.opcode == IBV_WC_SEND ||
	                    wc.opcode == IBV_WC_RDMA_WRITE ) {
			    		fprintf(stderr, "[%d->%d] send desc error, wc_opcode=%d\n",myrank, vc->pg_rank, wc.opcode );
	                } else {
			    		fprintf(stderr, "[%d<-%d] recv desc error, wc_opcode=%d\n",myrank, vc->pg_rank, wc.opcode);
					}
                    fprintf(stderr, "[%d->%d] wc.status=%d, wc.wr_id=%p, wc.opcode=%d, vbuf->phead->type=%d = %s\n", 
                           myrank, vc->pg_rank, wc.status, v, 
			               wc.opcode,((MPIDI_CH3I_MRAILI_Pkt_comm_header*)v->pheader)->type, 
           			MPIDI_CH3_Pkt_type_to_string[((MPIDI_CH3I_MRAILI_Pkt_comm_header*)v->pheader)->type] );
	
	                ibv_va_error_abort(IBV_STATUS_ERR,
	                        "[] Got completion with error %d, "
	                        "vendor code=0x%x, dest rank=%d\n",
	                        wc.status,    
	                        wc.vendor_err, 
	                        ((MPIDI_VC_t *)v->vc)->pg_rank
	                        );
	            }

                is_send_completion = (wc.opcode == IBV_WC_SEND
                    || wc.opcode == IBV_WC_RDMA_WRITE
                    || wc.opcode == IBV_WC_RDMA_READ);
	
                if (2 == num_cqs) {
    	            if (0 == cq_choice) {
    	                if (MPIDI_CH3I_RDMA_Process.global_used_send_cq) {
                             MPIDI_CH3I_RDMA_Process.global_used_send_cq--;
    	                } else {
                            DEBUG_PRINT("[%d] Possibly received a duplicate \
                                       send completion event \n", 
                                       MPIDI_Process.my_pg_rank);
    	                }
    	            } 
                } else {
                       if(is_send_completion && 
                              (MPIDI_CH3I_RDMA_Process.global_used_send_cq > 0)) {
                             MPIDI_CH3I_RDMA_Process.global_used_send_cq--;
                       } else {
                            DEBUG_PRINT("[%d] Possibly received a duplicate \
                                       send completion event \n",
                                       MPIDI_Process.my_pg_rank);
                       }     
                }
 
	            if(!is_send_completion && (MPIDI_CH3I_RDMA_Process.has_srq
                                    || v->transport == IB_TRANSPORT_UD)) {
                    SET_PKT_LEN_HEADER(v, wc);
                    SET_PKT_HEADER_OFFSET(v);
                    p = v->pheader;
#ifdef _ENABLE_UD_
                    MPIDI_PG_Get_vc(MPIDI_Process.my_pg, p->src.rank, &vc);
#else
                    vc = (MPIDI_VC_t *)p->src.vc_addr;
#endif
                    v->vc = vc;
                    v->rail = p->rail;
	            } 
	            
	            /* get the VC and increase its wqe */
	            if (is_send_completion) {
#ifdef _ENABLE_UD_
                if (rdma_enable_hybrid) {
                    if(v->transport == IB_TRANSPORT_RC  || 
                        (v->pheader && IS_CNTL_MSG(v->pheader))) {
                        MRAILI_Process_send(v);
                    }
                    if (v->transport == IB_TRANSPORT_UD) {
                        mv2_ud_update_send_credits(v);
                    }
                    if(v->transport == IB_TRANSPORT_UD &&
                            v->flags & UD_VBUF_SEND_INPROGRESS) {
                        v->flags &= ~(UD_VBUF_SEND_INPROGRESS);
                        if (v->flags & UD_VBUF_FREE_PENIDING) {
                            v->flags &= ~(UD_VBUF_FREE_PENIDING);
                            MRAILI_Release_vbuf(v);
                        }
                    }
                }
                else
#endif
                {
	                MRAILI_Process_send(v);
                }
                    type = T_CHANNEL_NO_ARRIVE;
                    *vbuf_handle = NULL;
	            } else if ((NULL == vc_req || vc_req == vc) && 0 == receiving ){
	                /* In this case, we should return the vbuf 
	                 * any way if it is next expected*/
	                int seqnum = GetSeqNumVbuf(v);
	                *vbuf_handle = v; 
                    SET_PKT_LEN_HEADER(v, wc);
                    SET_PKT_HEADER_OFFSET(v);
                    v->seqnum =  seqnum;
                    p = v->pheader;
                    PRINT_DEBUG(DEBUG_UD_verbose>1,"Received from rank:%d seqnum :%d ack:%d size:%d type:%d trasport :%d \n",vc->pg_rank, v->seqnum, p->acknum, v->content_size, p->type, v->transport);
#ifdef _ENABLE_UD_
                    if (v->transport == IB_TRANSPORT_UD)
                    {
                        mv2_ud_ctx_t *ud_ctx = 
                            MPIDI_CH3I_RDMA_Process.ud_rails[i];
                        --ud_ctx->num_recvs_posted;
                        if(ud_ctx->num_recvs_posted < ud_ctx->credit_preserve) {
                            ud_ctx->num_recvs_posted += mv2_post_ud_recv_buffers(
                                    (rdma_default_max_ud_recv_wqe - ud_ctx->num_recvs_posted), ud_ctx);
                        }
                    }
                    else
#endif 
                    if (MPIDI_CH3I_RDMA_Process.has_srq) {
	                    pthread_spin_lock(&MPIDI_CH3I_RDMA_Process.
	                            srq_post_spin_lock);
	
	                    if(v->padding == NORMAL_VBUF_FLAG) {
	                        /* Can only be from SRQ path */
	                        --MPIDI_CH3I_RDMA_Process.posted_bufs[i];
	                    }
	
	                    if(MPIDI_CH3I_RDMA_Process.posted_bufs[i] <= 
	                            rdma_credit_preserve) {
	                        /* Need to post more to the SRQ */
	                        MPIDI_CH3I_RDMA_Process.posted_bufs[i] +=
	                            viadev_post_srq_buffers(viadev_srq_fill_size - 
	                                MPIDI_CH3I_RDMA_Process.posted_bufs[i], i);
	
	                    }
	
	                    pthread_spin_unlock(&MPIDI_CH3I_RDMA_Process.
	                            srq_post_spin_lock);
	
	                    /* Check if we need to release the SRQ limit thread */
	                    if (MPIDI_CH3I_RDMA_Process.
	                            srq_zero_post_counter[i] >= 1) {
	                        pthread_mutex_lock(
	                                &MPIDI_CH3I_RDMA_Process.
	                                srq_post_mutex_lock[i]);
	                        MPIDI_CH3I_RDMA_Process.srq_zero_post_counter[i] = 0;
	                        pthread_cond_signal(&MPIDI_CH3I_RDMA_Process.
	                                srq_post_cond[i]);
	                        pthread_mutex_unlock(
	                                &MPIDI_CH3I_RDMA_Process.
	                                srq_post_mutex_lock[i]);
	                    }
	
	                }
	                else
	                {
	                    --vc->mrail.srp.credits[v->rail].preposts;
	
	                    needed = rdma_prepost_depth + rdma_prepost_noop_extra
	                             + MIN(rdma_prepost_rendezvous_extra,
	                                   vc->mrail.srp.credits[v->rail].
	                                   rendezvous_packets_expected);
	                }
#ifdef _ENABLE_UD_
                    if (rdma_enable_hybrid){
                        if (IS_CNTL_MSG(p)){
                            type = T_CHANNEL_CONTROL_MSG_ARRIVE;
                        } else {
                            type = T_CHANNEL_HYBRID_MSG_ARRIVE;
                        }
                    }
                    else
#endif
                    {
                        if (seqnum == PKT_NO_SEQ_NUM){
                            type = T_CHANNEL_CONTROL_MSG_ARRIVE;
                        } else if (seqnum == vc->mrail.seqnum_next_torecv) {
                            vc->mrail.seqnum_next_toack = vc->mrail.seqnum_next_torecv;
                            ++vc->mrail.seqnum_next_torecv;
                            type = T_CHANNEL_EXACT_ARRIVE;
                            DEBUG_PRINT("[channel manager] get one with exact seqnum\n");
                        } else {
                            type = T_CHANNEL_OUT_OF_ORDER_ARRIVE;
                            VQUEUE_ENQUEUE(&vc->mrail.cmanager, 
                                    INDEX_GLOBAL(&vc->mrail.cmanager, v->rail),
                                    v);
                            DEBUG_PRINT("get recv %d (%d)\n", seqnum, vc->mrail.seqnum_next_torecv);
                        }
                    }
	                if (!MPIDI_CH3I_RDMA_Process.has_srq && v->transport != IB_TRANSPORT_UD) {
                          
	                    if (PKT_IS_NOOP(v)) {
	                        PREPOST_VBUF_RECV(vc, v->rail);
	                        /* noops don't count for credits */
	                        --vc->mrail.srp.credits[v->rail].local_credit;
	                    } 
	                    else if ((vc->mrail.srp.credits[v->rail].preposts 
                                 < rdma_rq_size) &&
	                             (vc->mrail.srp.credits[v->rail].preposts + 
	                             rdma_prepost_threshold < needed))
	                    {
	                        do {
	                            PREPOST_VBUF_RECV(vc, v->rail);
	                        } while (vc->mrail.srp.credits[v->rail].preposts 
                                     < rdma_rq_size &&
	                                 vc->mrail.srp.credits[v->rail].preposts 
                                     < needed);
	                    }
	
	                    MRAILI_Send_noop_if_needed(vc, v->rail);
	                }
	
	                if (type == T_CHANNEL_CONTROL_MSG_ARRIVE || 
	                        type == T_CHANNEL_EXACT_ARRIVE ||
                            type == T_CHANNEL_HYBRID_MSG_ARRIVE || 
	                        type == T_CHANNEL_OUT_OF_ORDER_ARRIVE) {
	                    goto fn_exit;
	                }
	            } else {
	                /* Commenting out the assert - possible coding error
	                 * MPIU_Assert(0);
	                 */
	                /* Now since this is not the packet we want, we have to 
                     * enqueue it */
	                type = T_CHANNEL_OUT_OF_ORDER_ARRIVE;
	                *vbuf_handle = NULL;
	                v->content_size = wc.byte_len;
	                VQUEUE_ENQUEUE(&vc->mrail.cmanager,
	                        INDEX_GLOBAL(&vc->mrail.cmanager, v->rail),
	                        v);
                    if (v->transport != IB_TRANSPORT_UD) {
                        if (MPIDI_CH3I_RDMA_Process.has_srq) {
                            pthread_spin_lock(&MPIDI_CH3I_RDMA_Process.srq_post_spin_lock);

                            if(v->padding == NORMAL_VBUF_FLAG ) {
                                /* Can only be from SRQ path */
                                --MPIDI_CH3I_RDMA_Process.posted_bufs[i];
                            }

                            if(MPIDI_CH3I_RDMA_Process.posted_bufs[i] <= rdma_credit_preserve) {
                                /* Need to post more to the SRQ */
                                MPIDI_CH3I_RDMA_Process.posted_bufs[i] +=
                                    viadev_post_srq_buffers(viadev_srq_fill_size - 
                                            MPIDI_CH3I_RDMA_Process.posted_bufs[i], i);

                            }

                            pthread_spin_unlock(&MPIDI_CH3I_RDMA_Process.
                                    srq_post_spin_lock);
                        } else {
                            --vc->mrail.srp.credits[v->rail].preposts;

                            needed = rdma_prepost_depth + rdma_prepost_noop_extra
                                + MIN(rdma_prepost_rendezvous_extra,
                                        vc->mrail.srp.credits[v->rail].
                                        rendezvous_packets_expected);

                            if (PKT_IS_NOOP(v)) {
                                PREPOST_VBUF_RECV(vc, v->rail);
                                --vc->mrail.srp.credits[v->rail].local_credit;
                            }
                            else if ((vc->mrail.srp.credits[v->rail].preposts 
                                        < rdma_rq_size) &&
                                    (vc->mrail.srp.credits[v->rail].preposts + 
                                     rdma_prepost_threshold < needed)) {
                                do {
                                    PREPOST_VBUF_RECV(vc, v->rail);
                                } while (vc->mrail.srp.credits[v->rail].preposts 
                                        < rdma_rq_size && 
                                        vc->mrail.srp.credits[v->rail].preposts 
                                        < needed);
                            }
                            MRAILI_Send_noop_if_needed(vc, v->rail);
                        }
                    }
	            }
	        } else {
	            *vbuf_handle = NULL;
	            type = T_CHANNEL_NO_ARRIVE;
	            ++nspin;
	
	            /* Blocking mode progress */
	            if(rdma_use_blocking && is_blocking && nspin >= rdma_blocking_spin_count_threshold){
	                /* Okay ... spun long enough, now time to go to sleep! */
	
	#if (MPICH_THREAD_LEVEL == MPI_THREAD_MULTIPLE)
	                MPIU_THREAD_CHECK_BEGIN
	                MPID_Thread_mutex_unlock(&MPIR_ThreadInfo.global_mutex);
	                MPIU_THREAD_CHECK_END
	#endif
	                do {    
	                    ret = ibv_get_cq_event(
	                            MPIDI_CH3I_RDMA_Process.comp_channel[i], 
	                            &ev_cq, &ev_ctx);
	                    if (ret && errno != EINTR) {
	                        ibv_va_error_abort(IBV_RETURN_ERR,
	                                "Failed to get cq event: %d\n", ret);
	                    }       
	                } while (ret && errno == EINTR); 
	#if (MPICH_THREAD_LEVEL == MPI_THREAD_MULTIPLE)
	                MPIU_THREAD_CHECK_BEGIN
	                MPID_Thread_mutex_lock(&MPIR_ThreadInfo.global_mutex);
	                MPIU_THREAD_CHECK_END
	#endif
	
                    if (num_cqs == 1) {
		                if (ev_cq != MPIDI_CH3I_RDMA_Process.cq_hndl[i]) {
		                    ibv_error_abort(IBV_STATUS_ERR,
                                             "Event in unknown CQ\n");
		                }
		
	                   ibv_ack_cq_events(MPIDI_CH3I_RDMA_Process.cq_hndl[i], 1);
		
		                if (ibv_req_notify_cq(
                                    MPIDI_CH3I_RDMA_Process.cq_hndl[i], 0)) {
		                    ibv_error_abort(IBV_RETURN_ERR,
		                            "Couldn't request for CQ notification\n");
		                }
                    } else {
		                if (ev_cq == MPIDI_CH3I_RDMA_Process.send_cq_hndl[i]) {
	                        ibv_ack_cq_events(
                                    MPIDI_CH3I_RDMA_Process.send_cq_hndl[i], 1);
		
		                    if (ibv_req_notify_cq(
                                  MPIDI_CH3I_RDMA_Process.send_cq_hndl[i], 0)) {
		                        ibv_error_abort(IBV_RETURN_ERR,
		                           "Couldn't request for CQ notification\n");
		                    }
                        } else if (ev_cq == 
                                    MPIDI_CH3I_RDMA_Process.recv_cq_hndl[i]) {
	                        ibv_ack_cq_events(
                                    MPIDI_CH3I_RDMA_Process.recv_cq_hndl[i], 1);
		
		                    if (ibv_req_notify_cq(
                                  MPIDI_CH3I_RDMA_Process.recv_cq_hndl[i], 0)) {
		                        ibv_error_abort(IBV_RETURN_ERR,
		                           "Couldn't request for CQ notification\n");
		                    }
		                } else {
		                   ibv_error_abort(IBV_STATUS_ERR,
                                             "Event in unknown CQ\n");
                        }
                    }
	                nspin = 0;
	            }
	        }
        }
    }
Exemplo n.º 13
0
int MPIDI_CH3I_MRAILI_Waiting_msg(MPIDI_VC_t * vc, vbuf ** vbuf_handle, int blocking) 
{
    MRAILI_Channel_manager * cmanager = &vc->mrail.cmanager;
    int i = 0;
    int seq;
    int seq_expected = vc->mrail.seqnum_next_torecv;
    int type = T_CHANNEL_NO_ARRIVE;
    MPIDI_STATE_DECL(MPID_GEN2_MPIDI_CH3I_MRAILIWAITING_MSG);
    MPIDI_FUNC_ENTER(MPID_GEN2_MPIDI_CH3I_MRAILIWAITING_MSG);

    *vbuf_handle = NULL;

    if (blocking) {
        DEBUG_PRINT("{entering} solve_out_of_order next expected %d, channel %d, head %p (%d)\n", 
                vc->mrail.seqnum_next_torecv, cmanager->num_channels, 
                cmanager->msg_channels[0].v_queue_head,
                GetSeqNumVbuf(cmanager->msg_channels[0].v_queue_head));
    }

    for (; i < cmanager->num_channels; ++i)
    {
        seq = GetSeqNumVbuf(cmanager->msg_channels[i].v_queue_head);
        if (seq == seq_expected) {
            *vbuf_handle = VQUEUE_DEQUEUE(cmanager, i);
            type = T_CHANNEL_EXACT_ARRIVE;
            ++vc->mrail.seqnum_next_torecv;
            goto fn_exit;
        } else if (PKT_NO_SEQ_NUM == seq) {
            *vbuf_handle = VQUEUE_DEQUEUE(cmanager, i);
            type = T_CHANNEL_CONTROL_MSG_ARRIVE;
            goto fn_exit;
        } else if (PKT_IS_NULL == seq) {
            /* Do nothing */
        } else {
            *vbuf_handle = cmanager->msg_channels[i].v_queue_head;
            type = T_CHANNEL_OUT_OF_ORDER_ARRIVE;
        }
    }

    /* Obviously the packet with correct sequence hasn't arrived */
    while (blocking) {
        /* poll local subrails*/
        for (i = 0; i < cmanager->num_local_pollings; ++i) {
            seq = GetSeqNumVbuf(cmanager->msg_channels[INDEX_LOCAL(cmanager,i)].v_queue_head);
            if (seq == seq_expected) {
                *vbuf_handle = VQUEUE_DEQUEUE(cmanager, INDEX_LOCAL(cmanager,i));
                ++vc->mrail.seqnum_next_torecv;
                type = T_CHANNEL_EXACT_ARRIVE;
                goto fn_exit;
            } else if (seq == PKT_NO_SEQ_NUM) {
                *vbuf_handle = VQUEUE_DEQUEUE(cmanager, INDEX_LOCAL(cmanager,i));
                type = T_CHANNEL_CONTROL_MSG_ARRIVE;
                goto fn_exit;
            }
            else if (vc->mrail.rfp.in_polling_set) {
                *vbuf_handle = MPIDI_CH3I_RDMA_poll(vc);
                seq = GetSeqNumVbuf(*vbuf_handle);
                if (seq == seq_expected) {
                    type = T_CHANNEL_EXACT_ARRIVE;
                    ++vc->mrail.seqnum_next_torecv;
                    goto fn_exit;
                }
                else if( seq == PKT_NO_SEQ_NUM) {
                    type = T_CHANNEL_CONTROL_MSG_ARRIVE;
                    goto fn_exit;
                } else if (*vbuf_handle != NULL){
                    VQUEUE_ENQUEUE(cmanager, INDEX_LOCAL(cmanager,i), *vbuf_handle);
                    *vbuf_handle = NULL;
                }
            }
        }

        type = MPIDI_CH3I_MRAILI_Cq_poll(vbuf_handle, vc, 0, blocking);
        if (type != T_CHANNEL_NO_ARRIVE) {
            switch(type) {
                case (T_CHANNEL_EXACT_ARRIVE):
                    goto fn_exit;
                case (T_CHANNEL_OUT_OF_ORDER_ARRIVE):
                    continue;
                case (T_CHANNEL_CONTROL_MSG_ARRIVE):
                    goto fn_exit;
                default:
                    ibv_error_abort(GEN_ASSERT_ERR, "Unexpected return type\n");
                    break;
            }
        } else {

        }
    } 
fn_exit:
    if (blocking) {
        DEBUG_PRINT("{return} solve_out_of_order, type %d, next expected %d\n", 
                type, vc->mrail.seqnum_next_torecv);
    }
    MPIDI_FUNC_EXIT(MPID_GEN2_MPIDI_CH3I_MRAILIWAITING_MSG);
    return type;
}
Exemplo n.º 14
0
int MPIDI_CH3I_MRAILI_Get_next_vbuf(MPIDI_VC_t** vc_ptr, vbuf** vbuf_ptr) 
{
    *vc_ptr = NULL;
    *vbuf_ptr = NULL;
    VBUF_FLAG_TYPE size;
    int type;
    MPIDI_STATE_DECL(MPID_GEN2_MPIDI_CH3I_MRAILI_GET_NEXT_VBUF);
    MPIDI_FUNC_ENTER(MPID_GEN2_MPIDI_CH3I_MRAILI_GET_NEXT_VBUF);

    type = MPIDI_CH3I_MRAILI_Test_pkt(vbuf_ptr);

    switch(type)
    { 
    case T_CHANNEL_CONTROL_MSG_ARRIVE:
    case T_CHANNEL_EXACT_ARRIVE:
            *vc_ptr = (*vbuf_ptr)->vc;
        goto fn_exit;
    case T_CHANNEL_OUT_OF_ORDER_ARRIVE:
            type = T_CHANNEL_NO_ARRIVE;
            *vbuf_ptr = NULL;
        break;
    }

    if (num_rdma_buffer == 0)
    {
        goto fn_exit;
    }

    int i = 0;
    MPIDI_VC_t* vc = NULL;
    int seq;
    vbuf* v = NULL;
    volatile VBUF_FLAG_TYPE* tail = NULL;
    volatile VBUF_FLAG_TYPE* head = NULL;

    /* no msg is queued, poll rdma polling set */
    for (; i < MPIDI_CH3I_RDMA_Process.polling_group_size; ++i)
    {
        vc = MPIDI_CH3I_RDMA_Process.polling_set[i];
        seq  = GetSeqNumVbuf(vc->mrail.cmanager.msg_channels[INDEX_LOCAL(&vc->mrail.cmanager,0)].v_queue_head);

        if (seq == PKT_IS_NULL)
        {
            v = &(vc->mrail.rfp.RDMA_recv_buf[vc->mrail.rfp.p_RDMA_recv]);
            head = v->head_flag;

            if (*head && vc->mrail.rfp.p_RDMA_recv != vc->mrail.rfp.p_RDMA_recv_tail)
            {
                size = (*head & FAST_RDMA_SIZE_MASK);
                tail = (VBUF_FLAG_TYPE *) (v->buffer + size);
                /* If the tail has not received yet, than go ahead and
                ** poll next connection */
                if (*head != *tail) {
                    continue;
                }
                
                DEBUG_PRINT("Get one!\n");

                if (++vc->mrail.rfp.p_RDMA_recv >= num_rdma_buffer)
                {
                    vc->mrail.rfp.p_RDMA_recv = 0;
                }

                v->pheader = v->buffer;
                v->content_size = size;
                *head = 0;

                seq = GetSeqNumVbuf(v);

#ifdef _ENABLE_UD_
                if (rdma_enable_hybrid){
                    v->seqnum = seq;
                    type = T_CHANNEL_HYBRID_MSG_ARRIVE;
                    *vbuf_ptr = v;
                    *vc_ptr = v->vc;
                    PRINT_DEBUG(DEBUG_UD_verbose>1,"received seqnum:%d expected:%d vc_ptr:%p\n",seq, vc->mrail.seqnum_next_torecv, v->vc);
                    goto fn_exit;
                } 
                else
#endif
                {
                    if (seq == vc->mrail.seqnum_next_torecv)
                    {
                        DEBUG_PRINT("Get one exact seq: %d\n", seq);
                        type = T_CHANNEL_EXACT_ARRIVE;
                        ++vc->mrail.seqnum_next_torecv;
                        *vbuf_ptr = v;
                        *vc_ptr = v->vc;
                        goto fn_exit;
                    }
                    else if (seq == PKT_NO_SEQ_NUM)
                    {
                        type = T_CHANNEL_CONTROL_MSG_ARRIVE;
                        DEBUG_PRINT("[vbuf_local]: get control msg\n");
                        *vbuf_ptr = v;
                        *vc_ptr = v->vc;
                        goto fn_exit;
                    }
                    else
                    {
                        DEBUG_PRINT("Get one out of order seq: %d, expecting %d\n", seq, vc->mrail.seqnum_next_torecv);
                        VQUEUE_ENQUEUE(&vc->mrail.cmanager, INDEX_LOCAL(&vc->mrail.cmanager, 0), v);
                        continue;
                    }
                }
            }
            else
            {
                continue;
            }
        } 
        if (seq == vc->mrail.seqnum_next_torecv)
        {
            *vbuf_ptr = VQUEUE_DEQUEUE(&vc->mrail.cmanager, INDEX_LOCAL(&vc->mrail.cmanager, 0));
            *vc_ptr = (*vbuf_ptr)->vc;
            ++vc->mrail.seqnum_next_torecv;
            type = T_CHANNEL_EXACT_ARRIVE;
            goto fn_exit;
        }
        else if (seq == PKT_NO_SEQ_NUM)
        {
            *vbuf_ptr = VQUEUE_DEQUEUE(&vc->mrail.cmanager, INDEX_LOCAL(&vc->mrail.cmanager, 0));
            *vc_ptr = (*vbuf_ptr)->vc;
            type = T_CHANNEL_CONTROL_MSG_ARRIVE;
            goto fn_exit;
        }

    }

fn_exit:
    MPIDI_FUNC_EXIT(MPID_GEN2_MPIDI_CH3I_MRAILI_GET_NEXT_VBUF);
    return type;
}
Exemplo n.º 15
0
static int usbOpenDevice(union filedescriptor *fdp, int vendor, char *vendorName,
			 int product, char *productName, int usesReportIDs)
{
    GUID                                hidGuid;        /* GUID for HID driver */
    HDEVINFO                            deviceInfoList;
    SP_DEVICE_INTERFACE_DATA            deviceInfo;
    SP_DEVICE_INTERFACE_DETAIL_DATA     *deviceDetails = NULL;
    DWORD                               size;
    int                                 i, openFlag = 0;  /* may be FILE_FLAG_OVERLAPPED */
    int                                 errorCode = USB_ERROR_NOTFOUND;
    HANDLE                              handle = INVALID_HANDLE_VALUE;
    HIDD_ATTRIBUTES                     deviceAttributes;

    HidD_GetHidGuid(&hidGuid);
    deviceInfoList = SetupDiGetClassDevs(&hidGuid, NULL, NULL,
					 DIGCF_PRESENT | DIGCF_INTERFACEDEVICE);
    deviceInfo.cbSize = sizeof(deviceInfo);
    for(i=0;;i++){
        if(handle != INVALID_HANDLE_VALUE){
            CloseHandle(handle);
            handle = INVALID_HANDLE_VALUE;
        }
        if(!SetupDiEnumDeviceInterfaces(deviceInfoList, 0, &hidGuid, i, &deviceInfo))
            break;  /* no more entries */
        /* first do a dummy call just to determine the actual size required */
        SetupDiGetDeviceInterfaceDetail(deviceInfoList, &deviceInfo, NULL, 0, &size, NULL);
        if(deviceDetails != NULL)
            free(deviceDetails);
        deviceDetails = malloc(size);
        deviceDetails->cbSize = sizeof(*deviceDetails);
        /* this call is for real: */
        SetupDiGetDeviceInterfaceDetail(deviceInfoList, &deviceInfo, deviceDetails,
					size, &size, NULL);
        DEBUG_PRINT(("checking HID path \"%s\"\n", deviceDetails->DevicePath));
        /* attempt opening for R/W -- we don't care about devices which can't be accessed */
        handle = CreateFile(deviceDetails->DevicePath, GENERIC_READ|GENERIC_WRITE,
			    FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
			    openFlag, NULL);
        if(handle == INVALID_HANDLE_VALUE){
            DEBUG_PRINT(("opening failed: %d\n", (int)GetLastError()));
            /* errorCode = USB_ERROR_ACCESS; opening will always fail for mouse -- ignore */
            continue;
        }
        deviceAttributes.Size = sizeof(deviceAttributes);
        HidD_GetAttributes(handle, &deviceAttributes);
        DEBUG_PRINT(("device attributes: vid=%d pid=%d\n",
		     deviceAttributes.VendorID, deviceAttributes.ProductID));
        if(deviceAttributes.VendorID != vendor || deviceAttributes.ProductID != product)
            continue;   /* ignore this device */
        errorCode = USB_ERROR_NOTFOUND;
        if(vendorName != NULL && productName != NULL){
            char    buffer[512];
            if(!HidD_GetManufacturerString(handle, buffer, sizeof(buffer))){
                DEBUG_PRINT(("error obtaining vendor name\n"));
                errorCode = USB_ERROR_IO;
                continue;
            }
            convertUniToAscii(buffer);
            DEBUG_PRINT(("vendorName = \"%s\"\n", buffer));
            if(strcmp(vendorName, buffer) != 0)
                continue;
            if(!HidD_GetProductString(handle, buffer, sizeof(buffer))){
                DEBUG_PRINT(("error obtaining product name\n"));
                errorCode = USB_ERROR_IO;
                continue;
            }
            convertUniToAscii(buffer);
            DEBUG_PRINT(("productName = \"%s\"\n", buffer));
            if(strcmp(productName, buffer) != 0)
                continue;
        }
        break;  /* we have found the device we are looking for! */
    }
    SetupDiDestroyDeviceInfoList(deviceInfoList);
    if(deviceDetails != NULL)
        free(deviceDetails);
    if(handle != INVALID_HANDLE_VALUE){
	fdp->pfd = (void *)handle;
	errorCode = 0;
    }
    return errorCode;
}
Exemplo n.º 16
0
short saveClientState(ParseClientInternal *parseClient) {
#ifdef CLIENT_DEBUG
    DEBUG_PRINT("[Parse] Saving client state\r\n");
#endif /* CLIENT_DEBUG */

    snprintf(clientStateFileName, CLIENT_STATE_FILENAME_LEN, CLIENT_STATE_FILENAME, parseClient->applicationId);

    long clientStateFile = -1;

    sl_FsDel((unsigned char *)clientStateFileName, 0);

    short status = sl_FsOpen((unsigned char *)clientStateFileName,
            FS_MODE_OPEN_CREATE(65536, _FS_FILE_OPEN_FLAG_COMMIT | _FS_FILE_PUBLIC_WRITE),
            NULL, &clientStateFile);
    if (status < 0) {
#ifdef CLIENT_DEBUG
        if (status == SL_FS_ERR_NO_AVAILABLE_BLOCKS) {
             DEBUG_PRINT("[Parse] No available blocks. Need to flash your device file system...\r\n");
        }
#endif /* CLIENT_DEBUG */
        return status;
    }

    sl_FsClose(clientStateFile, 0, 0, 0);

    clientStateFile = -1;
    status = sl_FsOpen((unsigned char *)clientStateFileName, FS_MODE_OPEN_WRITE, NULL, &clientStateFile);
    if (status < 0) {
#ifdef CLIENT_DEBUG
        if (status == SL_FS_ERR_NO_AVAILABLE_BLOCKS) {
             DEBUG_PRINT("[Parse] No available blocks. Need to flash your device file system...\r\n");
        }
#endif /* CLIENT_DEBUG */
        sl_FsClose(clientStateFile, 0, 0, 0);
        return status;
    }

#ifdef CLIENT_DEBUG
    DEBUG_PRINT("[Parse] Installation Id: %s\r\n", parseClient->installationId);
#endif /* CLIENT_DEBUG */
    long writeOffset = 0;
    status = sl_FsWrite(clientStateFile, writeOffset, (unsigned char *)parseClient->installationId, sizeof(parseClient->installationId));
    if (status < 0) {
#ifdef CLIENT_DEBUG
        if (status == SL_FS_ERR_NO_AVAILABLE_BLOCKS) {
             DEBUG_PRINT("[Parse] No available blocks. Need to flash your device file system...\r\n");
        }
#endif /* CLIENT_DEBUG */
        sl_FsClose(clientStateFile, 0, 0, 0);
        return status;
    }

#ifdef CLIENT_DEBUG
    DEBUG_PRINT("[Parse] Session token: %s\r\n", parseClient->sessionToken);
#endif /* CLIENT_DEBUG */
    writeOffset = writeOffset + status;
    status = sl_FsWrite(clientStateFile, writeOffset, (unsigned char *)parseClient->sessionToken, sizeof(parseClient->sessionToken));
    if (status < 0) {
#ifdef CLIENT_DEBUG
        if (status == SL_FS_ERR_NO_AVAILABLE_BLOCKS) {
             DEBUG_PRINT("[Parse] No available blocks. Need to flash your device file system...\r\n");
        }
#endif /* CLIENT_DEBUG */
        sl_FsClose(clientStateFile, 0, 0, 0);
        return status;
    }

#ifdef CLIENT_DEBUG
    DEBUG_PRINT("[Parse] Last push time: %s\r\n", parseClient->lastPushTime);
#endif /* CLIENT_DEBUG */
    writeOffset = writeOffset + status;
    status = sl_FsWrite(clientStateFile, writeOffset, (unsigned char *)parseClient->lastPushTime, sizeof(parseClient->lastPushTime));
    if (status < 0) {
#ifdef CLIENT_DEBUG
        if (status == SL_FS_ERR_NO_AVAILABLE_BLOCKS) {
             DEBUG_PRINT("[Parse] No available blocks. Need to flash your device file system...\r\n");
        }
#endif /* CLIENT_DEBUG */
        sl_FsClose(clientStateFile, 0, 0, 0);
        return status;
    }

    sl_FsClose(clientStateFile, 0, 0, 0);

    return status;
}
Exemplo n.º 17
0
/*
 * Suspend processing
 */
SYSCALL INT tk_sus_dev_impl( UINT mode )
{
	ResCB	*rescb;
	BOOL	suspend = FALSE;
	ER	ercd;

	/* Get resource management information */
	rescb = knl_GetResCB();
	if ( rescb == NULL ) {
		ercd = E_CTX;
		goto err_ret1;
	}

	LockDM();

	switch ( mode & 0xf ) {
	  case TD_SUSPEND:	/* Suspend */
		if ( knl_DisSusCnt > 0 && (mode & TD_FORCE) == 0 ) {
			ercd = E_BUSY;
			goto err_ret2;
		}
		suspend = TRUE;
		break;

	  case TD_DISSUS:	/* Disable suspend */
		if ( knl_DisSusCnt >= MAX_DISSUS ) {
			ercd = E_QOVR;
			goto err_ret2;
		}
		knl_DisSusCnt++;
		rescb->dissus++;
		break;
	  case TD_ENASUS:	/* Enable suspend */
		if ( rescb->dissus > 0 ) {
			rescb->dissus--;
			knl_DisSusCnt--;
		}
		break;

	  case TD_CHECK:	/* Get suspend disable request count */
		break;

	  default:
		ercd = E_PAR;
		goto err_ret2;
	}

	UnlockDM();

	if ( suspend ) {
		/* Suspend */
		ercd = do_suspend();
		if ( ercd < E_OK ) {
			goto err_ret1;
		}
	}

	return knl_DisSusCnt;

err_ret2:
	UnlockDM();
err_ret1:
	DEBUG_PRINT(("tk_sus_dev_impl ercd = %d\n", ercd));
	return ercd;
}
Exemplo n.º 18
0
bool parse_header(uint64_t *address, s_acpi *acpi) {
	    s_acpi_description_header adh;
	    memset(&adh, 0, sizeof(adh));

	    get_acpi_description_header((uint8_t *)address, &adh);

	    /* Trying to determine the pointed table */
	    /* Looking for FADT */
	    if (memcmp(adh.signature, FACP, sizeof(FACP) - 1) == 0) {
		DEBUG_PRINT(("FACP table found\n"));
		s_fadt *f = &acpi->fadt;
		s_facs *fa = &acpi->facs;
		s_dsdt *d = &acpi->dsdt;
		/* This structure is valid, let's fill it */
		f->valid = true;
		f->address = address;
		memcpy(&f->header, &adh, sizeof(adh));
		parse_fadt(f);

		/* FACS wasn't already detected
		 * FADT points to it, let's try to detect it */
		if (fa->valid == false) {
		    fa->address = (uint64_t *)f->x_firmware_ctrl;
		    parse_facs(fa);
		    if (fa->valid == false) {
			/* Let's try again */
			fa->address = (uint64_t *)f->firmware_ctrl;
			parse_facs(fa);
		    }
		}

		/* DSDT wasn't already detected
		 * FADT points to it, let's try to detect it */
		if (d->valid == false) {
		    s_acpi_description_header new_adh;
		    get_acpi_description_header((uint8_t *)f->x_dsdt,
						&new_adh);
		    if (memcmp(new_adh.signature, DSDT, sizeof(DSDT) - 1) == 0) {
			DEBUG_PRINT(("DSDT table found via x_dsdt\n"));
			d->valid = true;
			d->address = (uint64_t *)f->x_dsdt;
			memcpy(&d->header, &new_adh, sizeof(new_adh));
			parse_dsdt(d);
		    } else {
			/* Let's try again */
			get_acpi_description_header((uint8_t *)f->dsdt_address,
						    &new_adh);
			if (memcmp(new_adh.signature, DSDT, sizeof(DSDT) - 1) ==
			    0) {
			    DEBUG_PRINT(("DSDT table found via dsdt_address\n"));
			    d->valid = true;
			    d->address = (uint64_t *)f->dsdt_address;
			    memcpy(&d->header, &new_adh, sizeof(new_adh));
			    parse_dsdt(d);
			}
		    }
		}
	    } /* Looking for MADT */
	    else if (memcmp(adh.signature, APIC, sizeof(APIC) - 1) == 0) {
		DEBUG_PRINT(("MADT table found\n"));
		s_madt *m = &acpi->madt;
		/* This structure is valid, let's fill it */
		m->valid = true;
		m->address =address;
		memcpy(&m->header, &adh, sizeof(adh));
		parse_madt(acpi);
	    } else if (memcmp(adh.signature, DSDT, sizeof(DSDT) - 1) == 0) {
		DEBUG_PRINT(("DSDT table found\n"));
		s_dsdt *d = &acpi->dsdt;
		/* This structure is valid, let's fill it */
		d->valid = true;
		d->address = address;
		memcpy(&d->header, &adh, sizeof(adh));
		parse_dsdt(d);
		/* PSDT have to be considered as SSDT. Intel ACPI Spec @ 5.2.11.3 */
	    } else if ((memcmp(adh.signature, SSDT, sizeof(SSDT) - 1) == 0)
		       || (memcmp(adh.signature, PSDT, sizeof(PSDT) - 1) == 0)) {
		
		DEBUG_PRINT(("SSDT table found with %s \n",adh.signature));

		if ((acpi->ssdt_count >= MAX_SSDT - 1))
		    return false;

		/* We can have many SSDT, so let's allocate a new one */
		if ((acpi->ssdt[acpi->ssdt_count] =
		     malloc(sizeof(s_ssdt))) == NULL)
		    return false;
		s_ssdt *s = acpi->ssdt[acpi->ssdt_count];

		/* This structure is valid, let's fill it */
		s->valid = true;
		s->address = address;
		memcpy(&s->header, &adh, sizeof(adh));

		/* Searching how much definition blocks we must copy */
		uint32_t definition_block_size = adh.length - ACPI_HEADER_SIZE;
		if ((s->definition_block =
		     malloc(definition_block_size)) != NULL) {
		    memcpy(s->definition_block,
			   (s->address + ACPI_HEADER_SIZE),
			   definition_block_size);
		}
		/* Increment the number of ssdt we have */
		acpi->ssdt_count++;
	    } else if (memcmp(adh.signature, SBST, sizeof(SBST) - 1) == 0) {
		DEBUG_PRINT(("SBST table found\n"));
		s_sbst *s = &acpi->sbst;
		/* This structure is valid, let's fill it */
		s->valid = true;
		s->address = address;
		memcpy(&s->header, &adh, sizeof(adh));
		parse_sbst(s);
	    } else if (memcmp(adh.signature, ECDT, sizeof(ECDT) - 1) == 0) {
		DEBUG_PRINT(("ECDT table found\n"));
		s_ecdt *e = &acpi->ecdt;
		/* This structure is valid, let's fill it */
		e->valid = true;
		e->address = address;
		memcpy(&e->header, &adh, sizeof(adh));
		parse_ecdt(e);
	    }  else if (memcmp(adh.signature, HPET, sizeof(HPET) - 1) == 0) {
		DEBUG_PRINT(("HPET table found\n"));
		s_hpet *h = &acpi->hpet;
		/* This structure is valid, let's fill it */
		h->valid = true;
		h->address = address;
		memcpy(&h->header, &adh, sizeof(adh));
	    } else if (memcmp(adh.signature, TCPA, sizeof(TCPA) - 1) == 0) {
		DEBUG_PRINT(("TCPA table found\n"));
		s_tcpa *t = &acpi->tcpa;
		/* This structure is valid, let's fill it */
		t->valid = true;
		t->address = address;
		memcpy(&t->header, &adh, sizeof(adh));
	    } else if (memcmp(adh.signature, MCFG, sizeof(MCFG) - 1) == 0) {
		DEBUG_PRINT(("MCFG table found\n"));
		s_mcfg *m = &acpi->mcfg;
		/* This structure is valid, let's fill it */
		m->valid = true;
		m->address = address;
		memcpy(&m->header, &adh, sizeof(adh));
	    } else if (memcmp(adh.signature, SLIC, sizeof(SLIC) - 1) == 0) {
		DEBUG_PRINT(("SLIC table found\n"));
		s_slic *s = &acpi->slic;
		/* This structure is valid, let's fill it */
		s->valid = true;
		s->address = address;
		memcpy(&s->header, &adh, sizeof(adh));
	    } else if (memcmp(adh.signature, BOOT, sizeof(BOOT) - 1) == 0) {
		DEBUG_PRINT(("BOOT table found\n"));
		s_boot *b = &acpi->boot;
		/* This structure is valid, let's fill it */
		b->valid = true;
		b->address = address;
		memcpy(&b->header, &adh, sizeof(adh));
	    }
	    
	    return true;
}
Exemplo n.º 19
0
/*
 * Device close processing
 */
EXPORT ER knl_close_device( OpnCB *opncb, UINT option )
{
	CLSFN	closefn;
	VP	exinf;
#if TA_GP
	VP	gp;
#endif
	ID	devid;
	DevCB	*devcb;
	INT	unitno;
	ER	ercd = E_OK;

	/* Abort all requests during processing */
	abort_allrequest(opncb);

	LockDM();

	devcb  = opncb->devcb;
	unitno = opncb->unitno;
	closefn = (CLSFN)devcb->ddev.closefn;
	exinf = devcb->ddev.exinf;
#if TA_GP
	gp = devcb->ddev.gp;
#endif
	devid = DEVID(devcb, unitno);

	/* Delete semaphore for completion check of abortion */
	tk_del_sem_impl(opncb->abort_semid);

	/* Free open management block */
	knl_delOpnCB(opncb, FALSE);

	/* Is device driver call required? */
	if ( knl_chkopen(devcb, unitno) ) {
		option &= ~TD_EJECT;
		if ( (devcb->ddev.drvatr & TDA_OPENREQ) == 0 ) {
			closefn = NULL;
		}
	}

	UnlockDM();

	if ( closefn != NULL ) {
		/* Device driver call */
		DISABLE_INTERRUPT;
		knl_ctxtsk->sysmode++;
		ENABLE_INTERRUPT;
#if TA_GP
		ercd = CallDeviceDriver(devid, option, exinf, 0, (FP)closefn, gp);
#else
		ercd = (*closefn)(devid, option, exinf);
#endif
		DISABLE_INTERRUPT;
		knl_ctxtsk->sysmode--;
		ENABLE_INTERRUPT;
	}

	LockDM();
	/* Return open management block to FreeQue */
	QueInsert(&opncb->q, &knl_FreeOpnCB);
	UnlockDM();

#ifdef DEBUG
	if ( ercd < E_OK ) {
		DEBUG_PRINT(("knl_close_device ercd = %d\n", ercd));
	}
#endif
	return ercd;
}
Exemplo n.º 20
0
jobject get_djvu_hyperlink_mapping(JNIEnv *jenv, ddjvu_document_t* djvu_document, ddjvu_pageinfo_t *page_info,
                                   miniexp_t sexp)
{
    miniexp_t iter;
    const char *url, *url_target;

    jobject hl = NULL;

    iter = sexp;

    if (miniexp_car(iter) != miniexp_symbol("maparea"))
    {
        DEBUG_PRINT("DjvuLibre error: Unknown hyperlink %s", miniexp_to_name(miniexp_car(sexp)));
        return hl;
    }

    iter = miniexp_cdr(iter);

    if (miniexp_caar(iter) == miniexp_symbol("url"))
    {
        if (!string_from_miniexp(miniexp_cadr(miniexp_car(iter)), &url))
        {
            DEBUG_PRINT("DjvuLibre error: Unknown hyperlink %s", miniexp_to_name(miniexp_car(sexp)));
            return hl;
        }
        if (!string_from_miniexp(miniexp_caddr(miniexp_car(iter)), &url_target))
        {
            DEBUG_PRINT("DjvuLibre error: Unknown hyperlink %s", miniexp_to_name(miniexp_car(sexp)));
            return hl;
        }
    }
    else
    {
        if (!string_from_miniexp(miniexp_car(iter), &url))
        {
            DEBUG_PRINT("DjvuLibre error: Unknown hyperlink %s", miniexp_to_name(miniexp_car(sexp)));
            return hl;
        }
        url_target = NULL;
    }

    iter = miniexp_cdr(iter);
    /* FIXME: DjVu hyperlink comments are ignored */

    int len = 0;
    int type;
    jint* data;
    iter = miniexp_cdr(iter);
    if ((data = get_djvu_hyperlink_area(page_info, miniexp_car(iter), type, len)) == NULL)
    {
        DEBUG_PRINT("DjvuLibre error: Unknown hyperlink %s", miniexp_to_name(miniexp_car(sexp)));
        return hl;
    }

    iter = miniexp_cdr(iter);
    /* FIXME: DjVu hyperlink attributes are ignored */

    DEBUG_PRINT("DjvuLibre: Hyperlink url: %s url_target: %s", url, url_target);

    if (!url)
    {
        delete[] data;
        return hl;
    }

    jclass pagelinkClass = jenv->FindClass("org/ebookdroid/core/codec/PageLink");
    if (!pagelinkClass)
    {
        delete[] data;
        return hl;
    }

    jmethodID plInitMethodId = jenv->GetMethodID(pagelinkClass, "<init>", "(Ljava/lang/String;I[I)V");
    if (!plInitMethodId)
    {
        delete[] data;
        return hl;
    }

    jintArray points = jenv->NewIntArray(len);
    jenv->SetIntArrayRegion(points, 0, len, data);

    jstring jstr = jenv->NewStringUTF(url);

    hl = jenv->NewObject(pagelinkClass, plInitMethodId, jstr, (jint) type, points);

    jenv->DeleteLocalRef(jstr);
    jenv->DeleteLocalRef(points);

    delete[] data;

//    DEBUG_PRINT("DjvuLibre: Hyperlink url: %s url_target: %s", url, url_target);

    return hl;

}
Exemplo n.º 21
0
/*
 * Request completion wait
 */
SYSCALL ID tk_wai_dev_impl( ID dd, ID reqid, W *asize, ER *ioer, TMO tmout )
{
	WAIFN	waitfn;
	VP	exinf;
#if TA_GP
	VP	gp;
#endif
	OpnCB	*opncb;
	DevCB	*devcb;
	ReqCB	*reqcb;
	T_DEVREQ *devreq;
	INT	reqno, nreq;
	ID	tskid;
	ER	ercd;

	tskid = tk_get_tid_impl();

	LockDM();

	ercd = knl_check_devdesc(dd, 0, &opncb);
	if ( ercd < E_OK ) {
		goto err_ret2;
	}

	devcb = opncb->devcb;
	waitfn = (WAIFN)devcb->ddev.waitfn;
	exinf = devcb->ddev.exinf;
#if TA_GP
	gp = devcb->ddev.gp;
#endif

	if ( reqid == 0 ) {
		/* When waiting for completion of any of requests for 'dd' */
		if ( opncb->nwaireq > 0 || opncb->waitone > 0 ) {
			ercd = E_OBJ;
			goto err_ret2;
		}
		if ( isQueEmpty(&opncb->requestq) ) {
			ercd = E_NOEXS;
			goto err_ret2;
		}

		/* Create wait request list */
		reqcb = (ReqCB*)opncb->requestq.next;
		for ( nreq = 1;; nreq++ ) {
			reqcb->tskid = tskid;
			devreq = &reqcb->req;
			reqcb = (ReqCB*)reqcb->q.next;
			if ( reqcb == (ReqCB*)&opncb->requestq ) {
				break;
			}
			devreq->next = &reqcb->req;
		}
		devreq->next = NULL;
		devreq = &((ReqCB*)opncb->requestq.next)->req;

		opncb->waireqlst = devreq;
		opncb->nwaireq = nreq;
	} else {
		/* Wait for completion of abort request processing */
		reqcb = knl_check_reqid(reqid, opncb);
		if ( reqcb == NULL ) {
			ercd = E_ID;
			goto err_ret2;
		}
		if ( opncb->nwaireq > 0 || reqcb->tskid > 0 ) {
			ercd = E_OBJ;
			goto err_ret2;
		}

		/* Create waiting request list */
		reqcb->tskid = tskid;
		devreq = &reqcb->req;
		devreq->next = NULL;
		nreq = 1;

		opncb->waitone++;
	}

	UnlockDM();

	/* Device driver call */
	DISABLE_INTERRUPT;
	knl_ctxtsk->sysmode++;
	ENABLE_INTERRUPT;
#if TA_GP
	reqno = CallDeviceDriver(devreq, nreq, tmout, exinf, (FP)waitfn, gp);
#else
	reqno = (*waitfn)(devreq, nreq, tmout, exinf);
#endif
	DISABLE_INTERRUPT;
	knl_ctxtsk->sysmode--;
	ENABLE_INTERRUPT;

	if ( reqno <  E_OK ) {
		ercd = reqno;
	}
	if ( reqno >= nreq ) {
		ercd = E_SYS;
	}

	LockDM();

	/* Free wait processing */
	if ( reqid == 0 ) {
		opncb->nwaireq = 0;
	} else {
		opncb->waitone--;
	}

	/* If there is an abort completion wait task,
	   notify abort completion */
	if ( opncb->abort_tskid > 0 && --opncb->abort_cnt == 0 ) {
		tk_sig_sem_impl(opncb->abort_semid, 1);
	}

	/* Get processing result */
	while ( devreq != NULL ) {
		reqcb = DEVREQ_REQCB(devreq);
		if ( reqno-- == 0 ) {
			reqid = REQID(reqcb);
			*asize = devreq->asize;
			*ioer  = devreq->error;
		}
		reqcb->tskid = 0;
		devreq = devreq->next;
	}

	if ( ercd < E_OK ) {
		goto err_ret2;
	}

	/* Unregister completed request */
	knl_delReqCB(REQCB(reqid));

	UnlockDM();

	return reqid;

err_ret2:
	UnlockDM();
	DEBUG_PRINT(("tk_wai_dev_impl ercd = %d\n", ercd));
	return ercd;
}
Exemplo n.º 22
0
extern "C" jlong Java_org_ebookdroid_droids_djvu_codec_DjvuDocument_getPage(JNIEnv *env, jclass cls, jlong docHandle,
                                                                          jint pageNumber)
{
    DEBUG_PRINT("getPage num: %d", pageNumber);
    return (jlong) ddjvu_page_create_by_pageno((ddjvu_document_t*) docHandle, pageNumber);
}
Exemplo n.º 23
0
PMT_ERROR createPmtTable(int iPid, int iProgNumber, PmtTable** ppsPmtTable)
{
    RootPidPacket* psTempPidRootNode;
    PacketNode*    psStartNode;
    ProgElement*   psTempProgElement;
    bool  bFoundPrivateSection;
    char* pcPrivateSectionAssembly;
    int   iCurrPos,iSectionLength,iBytesRead;

    psTempPidRootNode = getPidRootNode(iPid);
    if (psTempPidRootNode == NULL)
    {
        /*log*/
        DEBUG_PRINT("Coudn't find PMT PID 0x%02X\n",iPid);
        return PMT_INVALID_PID;
    }

    /* 
     * more then one PMT table can be carried on the same PID. We need to find private section
     * that has PMT table we are looking for here
    */
    bFoundPrivateSection = false;
    psStartNode = psTempPidRootNode->psThisPID;
    while (psStartNode && !bFoundPrivateSection)
    {
        pcPrivateSectionAssembly = assemblePrivateSection(psStartNode);
        if (pcPrivateSectionAssembly)
        {
            /*process private section*/
            if (pcPrivateSectionAssembly[FIRST_BYTE] == PMT_TABLE_ID)
            {
                iSectionLength = (((pcPrivateSectionAssembly[SECND_BYTE]&0xF)<<8)|pcPrivateSectionAssembly[THIRD_BYTE])&0x0FFF;
                /*check why we get negative section length*/
                if (iProgNumber == 9200)
                {
                    DEBUG_PRINT("iSectionLength = %d\n",iSectionLength);
                    DEBUG_PRINT("pcPrivateSectionAssembly[FORTH_BYTE]    = 0x%04X\n",pcPrivateSectionAssembly[FORTH_BYTE]&0xFF);
                    DEBUG_PRINT("pcPrivateSectionAssembly[FORTH_BYTE]<<8 = 0x%04X\n",pcPrivateSectionAssembly[FORTH_BYTE]&0xFF<<8);
                    DEBUG_PRINT("pcPrivateSectionAssembly[FIFTH_BYTE]    = 0x%04X\n",pcPrivateSectionAssembly[FIFTH_BYTE]&0xFF);
                    DEBUG_PRINT("((pcPrivateSectionAssembly[FORTH_BYTE]<<8)|pcPrivateSectionAssembly[FIFTH_BYTE]) 0x%04X\n",
                                ((pcPrivateSectionAssembly[FORTH_BYTE]&0xFF<<8)|(pcPrivateSectionAssembly[FIFTH_BYTE]&0xFF)));
                    DEBUG_PRINT("(int)((pcPrivateSectionAssembly[FORTH_BYTE]<<8)|pcPrivateSectionAssembly[FIFTH_BYTE]) 0x%04X\n",
                                (int)((pcPrivateSectionAssembly[FORTH_BYTE]&0xFF<<8)|(pcPrivateSectionAssembly[FIFTH_BYTE]&0xFF)));
                    DEBUG_PRINT("Candidate %d for PMT %d\n",
                                ((pcPrivateSectionAssembly[FORTH_BYTE]&0xFF<<8)|(pcPrivateSectionAssembly[FIFTH_BYTE]&0xFF)),
                                iProgNumber);
                }
                if ((int)((pcPrivateSectionAssembly[FORTH_BYTE]&0xFF<<8)|(pcPrivateSectionAssembly[FIFTH_BYTE]&0xFF)) == iProgNumber)
                {
                    DEBUG_PRINT("Found %d\n",iProgNumber);
                    bFoundPrivateSection = true;
                }
            }
        }
	    if (!bFoundPrivateSection)
        {
            //DEBUG_PRINT("Trying next packet\n");
            if(pcPrivateSectionAssembly != NULL)
            {
                free(pcPrivateSectionAssembly),pcPrivateSectionAssembly=NULL;
            }
            psStartNode = psStartNode->psNextPacket;
        }
    }

    if (!bFoundPrivateSection)
    {
        //DEBUG_PRINT("Could not find private section\n");
        return PMT_NOT_FOUND;
    }

    *ppsPmtTable = malloc(sizeof(PmtTable));
    memset(*ppsPmtTable,0,sizeof(PmtTable));

    (*ppsPmtTable)->iProgNumber      = iProgNumber;
    (*ppsPmtTable)->iVersionNumber   = (pcPrivateSectionAssembly[SIXTH_BYTE]&0x3E)>>1;
    (*ppsPmtTable)->bValidPmt        = pcPrivateSectionAssembly[SIXTH_BYTE]&0x1;
    (*ppsPmtTable)->iPcrPid          = (((pcPrivateSectionAssembly[NINTH_BYTE]&0x1F)<<8)|
		                               (pcPrivateSectionAssembly[TENTH_BYTE]&0xFF));
    (*ppsPmtTable)->iOuterDescLength = ((pcPrivateSectionAssembly[ELVTH_BYTE]&0x3)<<8)|
	                                   (pcPrivateSectionAssembly[TWVTH_BYTE]&0xFF);

    if ((*ppsPmtTable)->iOuterDescLength > 0)
    {
        (*ppsPmtTable)->pcOuterDesc = pcPrivateSectionAssembly + TWVTH_BYTE + 1;
    }
#if 0
    if (iProgNumber == 9216)
    {
        PacketNode* psFileNode;
        FILE*   fpPmtDump;
        int     iPrivCounter;

        fpPmtDump = fopen("./pmt9216.bin","w");
        for (iPrivCounter = 0; iPrivCounter < 64; iPrivCounter ++)
        {
            fwrite(pcPrivateSectionAssembly+iPrivCounter,1,1,fpPmtDump);
        }
        fclose(fpPmtDump);

        psFileNode = psStartNode;
        fpPmtDump = fopen("./pmt9216_tran.bin","w");
        for (iPrivCounter = 0; iPrivCounter < 2; iPrivCounter ++)
        {
            if ((psFileNode != NULL) && (psFileNode->pcPacketBuffer))
            {
                fwrite(psFileNode->pcPacketBuffer,188,1,fpPmtDump);
                psFileNode = psFileNode->psNextPacket;
            }
        }
        fclose(fpPmtDump);

    }
#endif

    DEBUG_PRINT("Outer Descriptor length = %d/%d\n",(*ppsPmtTable)->iOuterDescLength,(*ppsPmtTable)->iOuterDescLength&0xFF);
    iCurrPos = (*ppsPmtTable)->iOuterDescLength + TWVTH_BYTE + 1;
    DEBUG_PRINT("iSection Length = %d\n",iSectionLength);
    while (iCurrPos < iSectionLength-4)
    {
        DEBUG_PRINT("iCurrPos = %d\n",iCurrPos);
        if (createProgElement(pcPrivateSectionAssembly+iCurrPos,&iBytesRead,&psTempProgElement) == PMT_OK)
        {
            /*insert into PMT structure*/
            insertProgElementIntoPMT(*ppsPmtTable, psTempProgElement);
        }
        iCurrPos += iBytesRead;
    }
    return PMT_OK;
}
Exemplo n.º 24
0
extern "C" jobject Java_org_ebookdroid_droids_djvu_codec_DjvuPage_getPageLinks(JNIEnv *env, jclass cls,
                                                                                 jlong docHandle, jint pageNumber)
{
    DEBUG_PRINT("getPageLinks num: %d", pageNumber);
    return djvu_links_get_links(env, (ddjvu_document_t*) docHandle, pageNumber);
}
Exemplo n.º 25
0
/*
 * if iElementIdx is set to positive value, it will return inner loop descriptor,
 * if iElementIdx is set to negative value, it will return outer (PMT) descriptor
*/
PMT_ERROR getElementaryPrivateDescPayload(PmtTable* psPmtTable, int iElementIdx, int iDescIdx, 
		                          DescAttr* psDescAttr)
{
    int iTempDescIdx,iDescOffset,iDescLength;
    char* pcCurrent;
    char* pcRawDesc;

    if (iElementIdx >= 0)
    {
        ProgElement* psTempElementStream;

        if (getPmtElementStreamByIdx(psPmtTable,&psTempElementStream,iElementIdx) != PMT_OK)
        {
            DEBUG_PRINT("Did not find elementary stream\n");
            return PMT_NOT_FOUND;
        }
        pcCurrent   = psTempElementStream->pcProgElDesc;
        iDescLength = psTempElementStream->iProgElDescLength;
    }
    else
    {
        pcCurrent   = psPmtTable->pcOuterDesc;
        iDescLength = psPmtTable->iOuterDescLength;
    }

    if (pcCurrent == NULL)
    {
        DEBUG_PRINT("Did not find outer descriptor\n");
        memset(psDescAttr,0,sizeof(DescAttr));
        return PMT_NOT_FOUND;
    }


    pcRawDesc   = pcCurrent;
    iTempDescIdx = 0;
    iDescOffset = 0;
    while (iTempDescIdx != iDescIdx)
    {
        /*
	 * 2 is for descriptor tag plus descriptor length byte itself
	 * *(pcCurrent + 1) isthe descriptor length
	*/
        iDescOffset += 2 + *(pcCurrent + 1); 
        if (iDescOffset >= iDescLength/*psTempElementStream->iProgElDescLength*/)
        {
            memset(psDescAttr,0,sizeof(DescAttr));
            DEBUG_PRINT("Did not find descriptor\n");
            return PMT_NOT_FOUND;
        }
        pcCurrent = (char*)(pcRawDesc/*psTempElementStream->pcProgElDesc*/ + iDescOffset);
        iTempDescIdx += 1;
    }

    switch (psDescAttr->eParam)
    {
        case PMT_PRIVATE_DESCRIPTOR_TAG:
        {
            psDescAttr->uAttr.iDescTag = pcCurrent[0];
            break;
        }
        case PMT_PRIVATE_DESCRIPTOR_PAYLOAD:
        {
            psDescAttr->uAttr.sPayload.pcPayload = pcCurrent + 2;
            psDescAttr->uAttr.sPayload.iPayloadLength = pcCurrent[1];
            break;
        }
    }
 
    return PMT_OK;
}
Exemplo n.º 26
0
extern "C" jlong Java_org_ebookdroid_droids_djvu_codec_DjvuContext_create(JNIEnv *env, jclass cls)
{
    ddjvu_context_t* context = ddjvu_context_create(DJVU_DROID);
    DEBUG_PRINT("Creating context: %x", context);
    return (jlong) context;
}
Exemplo n.º 27
0
	NMErr
	dprintf_err(
		char	*message,
		NMErr	err,
		char		*file,
		NMSInt32	line)
	{
	char 	*name;
		
		if (err == SOCKET_ERROR)
			err = WSAGetLastError();
			
		switch (err)
		{
			PRINT_CASE(WSAEINTR);
			PRINT_CASE(WSAEBADF);
			PRINT_CASE(WSAEACCES);
			PRINT_CASE(WSAEFAULT);
			PRINT_CASE(WSAEINVAL);
			PRINT_CASE(WSAEMFILE);
			PRINT_CASE(WSAEWOULDBLOCK);
			PRINT_CASE(WSAEINPROGRESS);
			PRINT_CASE(WSAEALREADY);
			PRINT_CASE(WSAENOTSOCK);
			PRINT_CASE(WSAEDESTADDRREQ);
			PRINT_CASE(WSAEMSGSIZE);
			PRINT_CASE(WSAEPROTOTYPE);
			PRINT_CASE(WSAENOPROTOOPT);
			PRINT_CASE(WSAEPROTONOSUPPORT);
			PRINT_CASE(WSAESOCKTNOSUPPORT);
			PRINT_CASE(WSAEOPNOTSUPP);
			PRINT_CASE(WSAEPFNOSUPPORT);
			PRINT_CASE(WSAEAFNOSUPPORT);
			PRINT_CASE(WSAEADDRINUSE);
			PRINT_CASE(WSAEADDRNOTAVAIL);
			PRINT_CASE(WSAENETDOWN);
			PRINT_CASE(WSAENETUNREACH);
			PRINT_CASE(WSAENETRESET);
			PRINT_CASE(WSAECONNABORTED);
			PRINT_CASE(WSAECONNRESET);
			PRINT_CASE(WSAENOBUFS);
			PRINT_CASE(WSAEISCONN);
			PRINT_CASE(WSAENOTCONN);
			PRINT_CASE(WSAESHUTDOWN);
			PRINT_CASE(WSAETOOMANYREFS);
			PRINT_CASE(WSAETIMEDOUT);
			PRINT_CASE(WSAECONNREFUSED);
			PRINT_CASE(WSAELOOP);
			PRINT_CASE(WSAENAMETOOLONG);
			PRINT_CASE(WSAEHOSTDOWN);
			PRINT_CASE(WSAEHOSTUNREACH);
			PRINT_CASE(WSAENOTEMPTY);
			PRINT_CASE(WSAEPROCLIM);
			PRINT_CASE(WSAEUSERS);
			PRINT_CASE(WSAEDQUOT);
			PRINT_CASE(WSAESTALE);
			PRINT_CASE(WSAEREMOTE);
			PRINT_CASE(WSAEDISCON);
			PRINT_CASE(WSASYSNOTREADY);
			PRINT_CASE(WSAVERNOTSUPPORTED);
			PRINT_CASE(WSANOTINITIALISED);
			PRINT_CASE(WSAHOST_NOT_FOUND);
			PRINT_CASE(WSATRY_AGAIN);
			PRINT_CASE(WSANO_RECOVERY);
			PRINT_CASE(WSANO_DATA);
			default:
				name = "<unknown>";
				break;
		}

		DEBUG_PRINT("Winsock Err: %s - %s (%d) File: %s, %d", message, name, err,file, line);
		return err;
	}
Exemplo n.º 28
0
extern "C" jboolean Java_org_ebookdroid_droids_djvu_codec_DjvuPage_renderPageBitmap(JNIEnv *env, jclass cls,
                                                                                  jlong pageHangle, jint targetWidth,
                                                                                  jint targetHeight, jfloat pageSliceX,
                                                                                  jfloat pageSliceY,
                                                                                  jfloat pageSliceWidth,
                                                                                  jfloat pageSliceHeight,
                                                                                  jobject bitmap, jint rendermode)
{
//#ifdef USE_JNI_BITMAP_API

    DEBUG_WRITE("Rendering page bitmap");

    AndroidBitmapInfo info;
    void *pixels;

    int ret;

    if ((ret = NativeBitmap_getInfo(env, bitmap, &info)) < 0)
    {
        DEBUG_PRINT("AndroidBitmap_getInfo() failed ! error=%d", ret);
        return 0;
    }

    DEBUG_WRITE("Checking format");
//    if (info.format != ANDROID_BITMAP_FORMAT_RGBA_8888) {
//    	DEBUG_WRITE("Bitmap format is not RGBA_8888 !");
//            return 0;
//    }
    if (info.format != ANDROID_BITMAP_FORMAT_RGB_565)
    {
        DEBUG_WRITE("Bitmap format is not RGB_565 !");
        return 0;
    }

    DEBUG_WRITE("locking pixels");
    if ((ret = NativeBitmap_lockPixels(env, bitmap, &pixels)) < 0)
    {
        DEBUG_PRINT("AndroidBitmap_lockPixels() failed ! error=%d", ret);
        return 0;
    }

    ddjvu_page_t* page = (ddjvu_page_t*) ((pageHangle));
    ddjvu_rect_t pageRect;
    pageRect.x = 0;
    pageRect.y = 0;
    pageRect.w = targetWidth / pageSliceWidth;
    pageRect.h = targetHeight / pageSliceHeight;
    ddjvu_rect_t targetRect;
    targetRect.x = pageSliceX * targetWidth / pageSliceWidth;
    targetRect.y = pageSliceY * targetHeight / pageSliceHeight;
    targetRect.w = targetWidth;
    targetRect.h = targetHeight;
    unsigned int masks[] = { 0xF800, 0x07E0, 0x001F };
    ddjvu_format_t* pixelFormat = ddjvu_format_create(DDJVU_FORMAT_RGBMASK16, 3, masks);
//    unsigned int masks[] = {0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000};    
//    ddjvu_format_t* pixelFormat = ddjvu_format_create(DDJVU_FORMAT_RGBMASK32, 4, masks);

    ddjvu_format_set_row_order(pixelFormat, TRUE);
    ddjvu_format_set_y_direction(pixelFormat, TRUE);

//    jboolean result = ddjvu_page_render(page, DDJVU_RENDER_COLOR, &pageRect, &targetRect, pixelFormat, targetWidth * 4, (char*)pixels);
    jboolean result = ddjvu_page_render(page, (ddjvu_render_mode_t) rendermode, &pageRect, &targetRect, pixelFormat,
        targetWidth * 2, (char*) pixels);

    ddjvu_format_release(pixelFormat);

    NativeBitmap_unlockPixels(env, bitmap);

    return result;
//#else
//    DEBUG_WRITE("Rendering page bitmap not implemented");
//	return 0;
//#endif
}
Exemplo n.º 29
0
int SN_gams_solve(unsigned iter, optHandle_t Optr, char* sysdir, char* model, const char* base_name, SolverOptions* options, SN_GAMS_gdx* gdx_data)
{
  assert(gdx_data);
  SN_GAMS_NM_gdx* mat_for_gdx = gdx_data->mat_for_gdx;
  SN_GAMS_NV_gdx* vec_for_gdx = gdx_data->vec_for_gdx;
  SN_GAMS_NV_gdx* vec_from_gdx = gdx_data->vec_from_gdx;

  char msg[GMS_SSSIZE];
  int status;
  gamsxHandle_t Gptr = NULL;
  idxHandle_t Xptr = NULL;
  gmoHandle_t gmoPtr = NULL;
  double infos[4] = {0.};
  /* Create objects */

  DEBUG_PRINT("FC3D_AVI_GAMS :: creating gamsx object\n");
  if (! gamsxCreateD (&Gptr, sysdir, msg, sizeof(msg))) {
    fprintf(stderr, "Could not create gamsx object: %s\n", msg);
    return 1;
  }

  DEBUG_PRINT("FC3D_AVI_GAMS :: creating gdx object\n");
  if (! idxCreateD (&Xptr, sysdir, msg, sizeof(msg))) {
    fprintf(stderr, "Could not create gdx object: %s\n", msg);
    return 1;
  }

  DEBUG_PRINT("FC3D_AVI_GAMS :: creating gmo object\n");
  if (! gmoCreateD (&gmoPtr, sysdir, msg, sizeof(msg))) {
    fprintf(stderr, "Could not create gmo object: %s\n", msg);
    return 1;
  }

  /* create input and output gdx names*/
  char gdxFileName[GMS_SSSIZE];
  char solFileName[GMS_SSSIZE];
//  char paramFileName[GMS_SSSIZE];

  strncpy(gdxFileName, base_name, sizeof(gdxFileName));
  strncpy(solFileName, base_name, sizeof(solFileName));
  strncat(solFileName, "_sol", sizeof(solFileName) - strlen(solFileName) - 1);

  strncat(gdxFileName, ".gdx", sizeof(gdxFileName) - strlen(gdxFileName) - 1);
  strncat(solFileName, ".gdx", sizeof(solFileName) - strlen(solFileName) - 1);
//  strncat(paramFileName, ".txt", sizeof(paramFileName));

  /* XXX ParmFile is not a string option */
//  optSetStrStr(Optr, "ParmFile", paramFileName);
//  setDashedOptions("filename", gdxFileName, paramFileName);
   optSetStrStr(Optr, "User1", gdxFileName);
   optSetStrStr(Optr, "User2", solFileName);

   idxOpenWrite(Xptr, gdxFileName, "Siconos/Numerics NM_to_GDX", &status);
   if (status)
     idxerrorR(status, "idxOpenWrite");
   DEBUG_PRINT("FC3D_AVI_GAMS :: fc3d_avi-condensed.gdx opened\n");

   while (mat_for_gdx)
   {
     char mat_descr[30];
     assert(mat_for_gdx->name);
     assert(mat_for_gdx->mat);
     snprintf(mat_descr, sizeof(mat_descr), "%s matrix", mat_for_gdx->name);
     if ((status=NM_to_GDX(Xptr, mat_for_gdx->name, mat_descr, mat_for_gdx->mat))) {
       fprintf(stderr, "Model data for matrix %s not written\n", mat_for_gdx->name);
       infos[1] = (double)-ETERMINATE;
       goto fail;
     }
     DEBUG_PRINTF("GAMSlink :: %s matrix written\n", mat_for_gdx->name);
     mat_for_gdx = mat_for_gdx->next;
   }

   while (vec_for_gdx)
   {
     char vec_descr[30];
     assert(vec_for_gdx->name);
     assert(vec_for_gdx->vec);
     assert(vec_for_gdx->size > 0);
     snprintf(vec_descr, sizeof(vec_descr), "%s vector", vec_for_gdx->name);

     if ((status=NV_to_GDX(Xptr, vec_for_gdx->name, vec_descr, vec_for_gdx->vec, vec_for_gdx->size))) {
       fprintf(stderr, "Model data for vector %s not written\n", vec_for_gdx->name);
       infos[1] = (double)-ETERMINATE;
       goto fail;
     }
     DEBUG_PRINTF("FC3D_AVI_GAMS :: %s vector written\n", vec_for_gdx->name);
     vec_for_gdx = vec_for_gdx->next;

   }

  if (idxClose(Xptr))
    idxerrorR(idxGetLastError(Xptr), "idxClose");


//   cp(gdxFileName, "fc3d_avi-condensed.gdx");


  if ((status=CallGams(Gptr, Optr, sysdir, model))) {
    fprintf(stderr, "Call to GAMS failed\n");
    infos[1] = (double)-ETERMINATE;
    goto fail;
  }


  /************************************************
   * Read back solution
   ************************************************/
  idxOpenRead(Xptr, solFileName, &status);
  if (status)
    idxerrorR(status, "idxOpenRead");

  while (vec_from_gdx)
  {
    assert(vec_from_gdx->name);
    assert(vec_from_gdx->vec);
    assert(vec_from_gdx->size > 0);
    double* data = vec_from_gdx->vec;
    unsigned size = vec_from_gdx->size;
    /* GAMS does not set a value to 0 ... --xhub */
    memset(data, 0, size*sizeof(double));
    if ((status=GDX_to_NV(Xptr, vec_from_gdx->name, data, size))) {
      fprintf(stderr, "Model data %s could not be read\n", vec_from_gdx->name);
      infos[1] = (double)-ETERMINATE;
      goto fail;
    }
    vec_from_gdx = vec_from_gdx->next;
  }

  if ((status=GDX_to_NV(Xptr, "infos", infos, sizeof(infos)/sizeof(double)))) {
    fprintf(stderr, "infos could not be read\n");
    infos[1] = (double)-ETERMINATE;
    goto fail;
  }

  if (idxClose(Xptr))
    idxerrorR(idxGetLastError(Xptr), "idxClose");

  options->iparam[TOTAL_ITER] += (int)infos[2];
  options->iparam[LAST_MODEL_STATUS] = (int)infos[0];
  options->iparam[LAST_SOLVE_STATUS] = (int)infos[1];
  options->dparam[TOTAL_TIME_USED] += infos[3];
  printf("SolveStat = %d, ModelStat = %d\n", (int)infos[1], (int)infos[0]);
  gmoGetModelStatusTxt(gmoPtr, (int)infos[0], msg);
  DEBUG_PRINTF("%s\n", msg);
  gmoGetSolveStatusTxt(gmoPtr, (int)infos[1], msg);
  DEBUG_PRINTF("%s\n", msg);

fail:
  idxFree(&Xptr);
  gamsxFree(&Gptr);
  gmoFree(&gmoPtr);
  return (int)infos[1];
}
Exemplo n.º 30
0
static uint8_t search_861_mode(sync_info_type *p_sync_info)
{
    int i;
    uint8_t detected_video_idx = SI_VIDEO_MODE_NON_STD;
    int16_t range;

    enum
    {
        not_found = 0,
        found_not_exact = 1,
        found_exact = 2
    }
    search_result = not_found;

    for(i=0; VideoModeTable[i].Vic4x3 || VideoModeTable[i].Vic16x9; i++)
    {
        const videoMode_t *p_video_table = &VideoModeTable[i];
        bool_t interlaced = p_sync_info->Interlaced;
        uint16_t total_V_lines_measured =
            (interlaced ?
             (p_sync_info->TotalLines * 2)
             : p_sync_info->TotalLines);

        // check progressive/interlaced
        if(interlaced != p_video_table->Interlaced)
            continue;

        // check number of lines
        if(ABS_DIFF(total_V_lines_measured, p_video_table->Total.V) > LINES_TOLERANCE)
            continue;

        // check number of clocks per line (it works for all possible replications)
        if(ABS_DIFF(p_sync_info->ClocksPerLine, p_video_table->Total.H) > PIXELS_TOLERANCE)
            continue;

        // check Pixel Freq (in 10kHz units)
//		if(ABS_DIFF(p_sync_info->PixelFreq, p_video_table->PixClk) > FPIX_TOLERANCE)  // tolerance based on fixed bandwidth
        if (0 != ABS_DIFF(p_sync_info->PixelFreq, p_video_table->PixClk))  // tolerance based on dynamic bandwidth (fixed ratio)
        {
            range = p_video_table->PixClk / ABS_DIFF(p_sync_info->PixelFreq, p_video_table->PixClk);

            if( (range) < FPIX_TOLERANCE_RANGE)    // per PLL range
                continue;
        }

#if 0        // enable it for mode search tuning
        DEBUG_PRINT(MSG_STAT,
                    "Index in table: %d, interlaced: %d, range: %d",
                    (int) i, (int) interlaced, (int)range);

        DEBUG_PRINT(MSG_STAT,
                    "Pixel Freq detected: %d, Pixel Freq in video table: %d",
                    (int) p_sync_info->PixelFreq, (int) p_video_table->PixClk);

        DEBUG_PRINT(MSG_STAT,
                    "clock per lines detected: %d, lines detected: %d",
                    (int) p_sync_info->ClocksPerLine, (int) total_V_lines_measured);

        DEBUG_PRINT(MSG_STAT,
                    "clock per lines in video table: %d, lines in video table: %d\n",
                    (int) p_video_table->Total.H, (int) p_video_table->Total.V);
#endif

        // if all previous tests passed, then we found at least one mode even polarity is mismatched
        if(search_result == not_found)
        {
            search_result = found_not_exact;
            detected_video_idx = i;
        }

        // check exact number of lines
        if(ABS_DIFF(total_V_lines_measured, p_video_table->Total.V) > 1)
            continue;

        // check polarities
        if(
            (p_sync_info->HPol == p_video_table->HPol) &&
            (p_sync_info->VPol == p_video_table->VPol)
        )
        {
            // if all previous checks passed
            search_result = found_exact;
            detected_video_idx = i;
            break;
        }
    }

    switch(search_result)
    {
    case not_found:
        break;
    case found_exact:
        break;
    case found_not_exact:
        DEBUG_PRINT(MSG_STAT, ("RX: Warning: not exact video mode found\n"));
        break;
    }

    return detected_video_idx;
}