int main(int argc, char * argv[]) {
    CmdLineOpts_t options = parseCmdLineArgs(argc, argv);

    int i,j;

    FP * h_A, * h_B, * h_C; // host matrices

    int sizeA = options.n * options.p * sizeof(FP); 
    int sizeB = options.p * options.m * sizeof(FP); 
    int sizeC = options.n * options.m * sizeof(FP);

    if (! (h_A = (FP*) malloc(sizeA)) ) DIE("Failed malloc");
    if (! (h_B = (FP*) malloc(sizeB)) ) DIE("Failed malloc");
    if (! (h_C = (FP*) malloc(sizeC)) ) DIE("Failed malloc");
    
    srand(12345);

    /* INIT MATRICES */
    for (i = 0; i < options.n; ++i) {
        for (j = 0; j < options.p; ++j) {
            h_A[i*options.p+j] = (FP) rand() / (FP) RAND_MAX;
        }
    }

    for (i = 0; i < options.p; ++i) {
        for (j = 0; j < options.m; ++j) {
            h_B[i*options.m+j] = (FP) rand() / (FP) RAND_MAX;
        }
    }

    for (i = 0; i < options.n * options.m; ++i) {
        h_C[i] = (FP) 0;
    }

    cpu_matrixmult(h_A, h_B, h_C, 
        options.n, options.p, options.m); // do calculation on host

    printMatrix(h_C, options.n, options.m);
    
    free(h_A);
    free(h_B);
    free(h_C);

    return 0;
}
Пример #2
0
// main
// Given that this is a very straight forward benchark the code is almost
// entirely kept within the main function.
// The steps taken in this code are the following:
// 1 - command line parsing
// 2 - data allocation and initialization
// 3 - jacobi 1D timed within an openmp loop
// 4 - output and optional verification
//
int main( int argc, char* argv[] ){

  // rather than calling fflush    
  setbuf(stdout, NULL); 

  // 1 - command line parsing
  Params cmdLineArgs;
  parseCmdLineArgs(&cmdLineArgs,argc,argv);


  // 2 - data allocation and initialization
  int lowerBound = 1;
  int upperBound = lowerBound + cmdLineArgs.problemSize - 1; 
  double* space[2] = { NULL, NULL }; 

  // allocate time-steps 0 and 1
  space[0] = (double*) malloc( (cmdLineArgs.problemSize + 2) * sizeof(double));
  space[1] = (double*) malloc( (cmdLineArgs.problemSize + 2) * sizeof(double));
  if( space[0] == NULL || space[1] == NULL ){
    printf( "Could not allocate space array\n" );
    exit(0);
  }
  
  // use global seed to seed the random number gen (will be constant)
  srand(cmdLineArgs.globalSeed);
  // seed the space.
  int idx;
  // the randome number generator is not thread safe -- so first
  // set everything to 0 - respecting first touch
  for( idx = lowerBound-1; idx <= upperBound+1; ++idx ){
    space[0][idx] = 0;
  }
  for( idx = lowerBound; idx <= upperBound; ++idx ){
    space[0][idx] = rand() / (double)rand();
  }
  // set halo values (sanity)
  space[0][0] = 0;
  space[0][upperBound+1] = 0;
  space[1][0] = 0;
  space[1][upperBound+1] = 0;
  // end allocate and initialize space
  
  // 3 - jacobi 1D timed within an openmp loop
  // Begin timed test  
  int t,  read = 0, write = 1;
  double start_time = omp_get_wtime();
    
  for( t = 1; t <= cmdLineArgs.T; ++t ){
    for( idx = lowerBound; idx <= upperBound; ++idx ){
      space[write][idx] = (space[read][idx-1] +
                         space[read][idx] +
                         space[read][idx+1])/3;
    }
    read = write;
    write = 1 - write;
  }
  double end_time = omp_get_wtime();
  double time =  end_time - start_time;
  // End timed test

  // 4 - output and optional verification
  /*
  printf( "p: %d, T: %d, c:%d",cmdLineArgs.problemSize,cmdLineArgs.T,
                               cmdLineArgs.cores);
                               */
  if( cmdLineArgs.printtime ){
    printf( "Time: %f", time );
  }//else{
    //printf( "\n" );
  //}

    
  if( cmdLineArgs.verify ){
    if(!verifyResultJacobi1D(space[cmdLineArgs.T & 1],cmdLineArgs.problemSize,
                             cmdLineArgs.globalSeed,cmdLineArgs.T )){
      fprintf(stderr,"FAILURE\n");
    }else{
      fprintf(stderr,"SUCCESS\n");
    } 
  }
  return 0; 
}
Пример #3
0
int main(int argc, char **argv)
#endif
{
	sslSessionId_t		*sessionId;
	sslConn_t			*conn;
	sslKeys_t			*keys;
	WSADATA				wsaData;
	SOCKET				fd;
	short				cipherSuite;
	unsigned char		*ip, *c, *requestBuf;
	unsigned char		buf[1024];
	int					iterations, requests, connectAgain, status;
	int					quit, rc, bytes, i, j, err;
	time_t				t0, t1;
#if REUSE
	int					anonStatus;
#endif
#if VXWORKS
	int					argc;
	char				**argv;
	parseCmdLineArgs(arg1, &argc, &argv);
#endif /* VXWORKS */

#if WINCE
	int					argc;
	char				**argv;
	char				args[256];

/*
 *	parseCmdLineArgs expects an ASCII string and CE is unicoded, so convert
 *	the command line.  args will get hacked up, so you can't pass in a
 *	static string.
 */
	WideCharToMultiByte(CP_ACP, 0, lpCmdLine, -1, args, 256, NULL, NULL);

/*
 *	Parse the command line into an argv array.  This allocs memory, so
 *	we have to free argv when we're done.
 */
	parseCmdLineArgs(args, &argc, &argv);
#endif /* WINCE */

	conn = NULL;
/*
	First (optional) argument is ip address to connect to (port is hardcoded)
	Second (optional) argument is number of iterations to perform
	Third (optional) argument is number of keepalive HTTP requests
	Fourth (optional) argument is cipher suite number to use (0 for any)
*/
	ip = HTTPS_IP;
	iterations = ITERATIONS;
	requests = REQUESTS;
	cipherSuite = 0x0000;
	if (argc > 1) {
		ip = argv[1];
		if (argc > 2) {
			iterations = atoi(argv[2]);
			socketAssert(iterations > 0);
			if (argc > 3) {
				requests = atoi(argv[3]);
				socketAssert(requests > 0);
				if (argc > 4) {
					cipherSuite = (short)atoi(argv[4]);
				}
			}
		}
	}
/*
	Initialize Windows sockets (no-op on other platforms)
*/
	WSAStartup(MAKEWORD(1,1), &wsaData);
/*
	Initialize the MatrixSSL Library, and read in the certificate file
	used to validate the server.
*/
	if (matrixSslOpen() < 0) {
		fprintf(stderr, "matrixSslOpen failed, exiting...");
	}
	sessionId = NULL;
	if (matrixSslReadKeys(&keys, NULL, NULL, NULL, CAfile) < 0) {
		goto promptAndExit;
	}
/*
	Intialize loop control variables
*/
	quit = 0;
	connectAgain = 1;
	i = 1;
/*
	Just reuse the requestBuf and malloc to largest possible message size
*/
	requestBuf = malloc(sizeof(requestAgain));
	t0 = time(0);
/*
	Main ITERATIONS loop
*/
	while (!quit && (i < iterations)) {
/*
		sslConnect uses port and ip address to connect to SSL server.
		Generates a new session
*/
		if (connectAgain) {
			if ((fd = socketConnect(ip, HTTPS_PORT, &err)) == INVALID_SOCKET) {
				fprintf(stdout, "Error connecting to server %s:%d\n", ip, HTTPS_PORT);
				matrixSslFreeKeys(keys);
				goto promptAndExit;
			}
			if (sslConnect(&conn, fd, keys, sessionId, cipherSuite, certChecker) < 0) {
				quit = 1;
				socketShutdown(fd);
				fprintf(stderr, "Error connecting to %s:%d\n", ip, HTTPS_PORT);
				continue;
			}
			i++;
			connectAgain = 0;
			j = 1;
		}
		if (conn == NULL) {
			quit++;
			continue;
		}
/*
		Copy the HTTP request header into the buffer, based of whether or
		not we want httpReflector to keep the socket open or not
*/
		if (j == requests) {
			bytes = (int)strlen(request);
			memcpy(requestBuf, request, bytes);
		} else {
			bytes = (int)strlen(requestAgain);
			memcpy(requestBuf, requestAgain, bytes);
		}
/*
		Send request.  
		< 0 return indicates an error.
		0 return indicates not all data was sent and we must retry
		> 0 indicates that all requested bytes were sent
*/
writeMore:
		rc = sslWrite(conn, requestBuf, bytes, &status);
		if (rc < 0) {
			fprintf(stdout, "Internal sslWrite error\n");
			socketShutdown(conn->fd);
			sslFreeConnection(&conn);
			continue;
		} else if (rc == 0) {
			goto writeMore;
		}
/*
		Read response
		< 0 return indicates an error.
		0 return indicates an EOF or CLOSE_NOTIFY in this situation
		> 0 indicates that some bytes were read.  Keep reading until we see
		the /r/n/r/n from the response header.  There may be data following
		this header, but we don't try too hard to read it for this example.
*/
		c = buf;
readMore:
		if ((rc = sslRead(conn, c, sizeof(buf) - (int)(c - buf), &status)) > 0) {
			c += rc;
			if (c - buf < 4 || memcmp(c - 4, "\r\n\r\n", 4) != 0) {
				goto readMore;
			}
		} else {
			if (rc < 0) {
				fprintf(stdout, "sslRead error.  dropping connection.\n");
			}
			if (rc < 0 || status == SSLSOCKET_EOF ||
					status == SSLSOCKET_CLOSE_NOTIFY) {
				socketShutdown(conn->fd);
				sslFreeConnection(&conn);
				continue;
			}
			goto readMore;
		}
/*
		Determine if we want to do a pipelined HTTP request/response
*/
		if (j++ < requests) {
			fprintf(stdout, "R");
			continue;
		} else {
			fprintf(stdout, "C");
		}
/*
		Reuse the session.  Comment out these two lines to test the entire
		public key renegotiation each iteration
*/
#if REUSE
		matrixSslFreeSessionId(sessionId);
		matrixSslGetSessionId(conn->ssl, &sessionId);
/*
		This example shows how a user might want to limit a client to
		resuming handshakes only with authenticated servers.  In this
		example, the client will force any non-authenticated (anonymous)
		server to go through a complete handshake each time.  This is
		strictly an example of one policy decision an implementation 
		might wish to make.
*/
		matrixSslGetAnonStatus(conn->ssl, &anonStatus);
		if (anonStatus) {
			matrixSslFreeSessionId(sessionId);
			sessionId = NULL;
		}
#endif
/*
		Send a closure alert for clean shutdown of remote SSL connection
		This is for good form, some implementations just close the socket
*/
		sslWriteClosureAlert(conn);
/*
		Session done.  Connect again if more iterations remaining
*/
		socketShutdown(conn->fd);
		sslFreeConnection(&conn);
		connectAgain = 1;
	}

	t1 = time(0);
	free(requestBuf);
	matrixSslFreeSessionId(sessionId);
	if (conn && conn->ssl) {
		socketShutdown(conn->fd);
		sslFreeConnection(&conn);
	}
	fprintf(stdout, "\n%d connections in %d seconds (%f c/s)\n", 
		i, (int)(t1 - t0), (double)i / (t1 - t0));
	fprintf(stdout, "\n%d requests in %d seconds (%f r/s)\n", 
		i * requests, (int)(t1 - t0), 
		(double)(i * requests) / (t1 - t0));
/*
	Close listening socket, free remaining items
*/
	matrixSslFreeKeys(keys);
	matrixSslClose();
	WSACleanup();
promptAndExit:
	fprintf(stdout, "Press return to exit...\n");
	getchar();

#if WINCE || VXWORKS
	if (argv) {
		free((void*) argv);
	}
#endif /* WINCE */
	return 0;
}
Пример #4
0
int main(int argc, char **argv)
#endif
{
	SOCKET			srv_fd;
	int				status;
	WSADATA			wsaData;
	
	// options
	char				*srv_host = NULL;
	int				srv_port = 0;
	char 				*keyfile = NULL; //"privkeySrv.pem";
	char 				*certfile = NULL; //"certSrv.pem";
	int				vlevel = 0;
	char 				*cpos,*opos;
	int tmpport;
	int c;
	int 			intarg;
 	
#if VXWORKS
	int					argc;
	char				**argv;
	parseCmdLineArgs(arg1, &argc, &argv);
#endif /* VXWORKS */

#if WINCE
	int					argc;
	char				**argv;
	char				args[256];

/*
 *	parseCmdLineArgs expects an ASCII string and CE is unicoded, so convert
 *	the command line.  args will get hacked up, so you can't pass in a
 *	static string.
 */
	WideCharToMultiByte(CP_ACP, 0, lpCmdLine, -1, args, 256, NULL, NULL);

/*
 *	Parse the command line into an argv array.  This allocs memory, so
 *	we have to free argv when we're done.
 */
	parseCmdLineArgs(args, &argc, &argv);
#endif /* WINCE */


/*
	prepare
*/
	
#ifndef USE_FORK
	memset(connections,0,MAXPROXYCOUNT*sizeof(struct proxyConnection));
#endif
	
/*
	getopt
*/
	/* Gemtek add +++ */
	if(argc == 1) usage(1);
	/* Gemtek add --- */
	
	for (;;) {
		c = getopt (argc, argv, "VD:P:fo:cd:r:p:A:v:h");
		if (c == -1) {
			break;
		}

		switch (c) {
			case 'c':
				// client mode
				isClient=1;
				break;
			
			case 'd':
				// daemon mode [host:]port
				cpos = NULL;
				tmpport = 0;
				if((cpos = strchr(optarg,':'))) {				
					*cpos = '\0';
					if(optarg && optarg[0])
						srv_host = optarg;
					optarg = ++cpos;
				}
				if(optarg && optarg[0]) {
					tmpport = (int)strtol(optarg, (char **)NULL, 0);
					if(tmpport) srv_port = tmpport;
				}
				break;
			
			case 'r':
				// remote [host:]port
				cpos = NULL;
				tmpport = 0;
				if((cpos = strchr(optarg,':'))) {				
					*cpos = '\0';
					if(optarg && optarg[0])
						dst_host = optarg;
					optarg = ++cpos;
				}
				if(optarg && optarg[0]) {
					tmpport = (int)strtol(optarg, (char **)NULL, 0);
					if(tmpport) dst_port = tmpport;
				}
				break;
				
			case 'p':
				// pemfile (requred in servermode)
				keyfile = optarg;
				break;
			
			case 'A':
				// CA file
				certfile = optarg;
				break;
			
			case 'v':
				// veryfication level
				if(optarg && optarg[0]) {
					vlevel = (int)strtol(optarg, (char **)NULL, 0);
					if(vlevel == 1 ) {
						cervalidator = certChecker;
					}
					else if(vlevel > 3 || vlevel < 0) {
						fprintf(stderr,"-v takes whole numbers between 0 and 3");
						exit(2);
					}
				}
				break;
			
			case 'P':
				// create a pidfile
				pidfile=optarg;
				break;
				
			case 'f':
				// run in foreground.
				nofork=1;
				nosysl=1;
				break;
				
			case 'o':
				// append logmessages to a file instead of stdout/syslog
				break;
				
			case 'O':
				// socket options. TODO
				break;
			
			case 'D':
				// debug level 0...7
				intarg=strtol(optarg,NULL,0);
				if(intarg<0 || intarg>7) {
					usage(1);
				}
				gLogLevel=intarg;
				break;
				
			case 'V':
				// version
				break;
				
			case '?':
			case 'h':
				usage(0);
				break;
			
			default:
				usage(1);
				break;
		}
	}


/* install handlers */
	signal( SIGPIPE, SIG_IGN );
	signal(SIGCHLD,sigchld_handler); /* ignore child */
	signal(SIGHUP,kill_handler); /* catch hangup signal */
	signal(SIGTERM,kill_handler); /* catch kill signal */
	
/*
	Initialize Windows sockets (no-op on other platforms)
*/
	WSAStartup(MAKEWORD(1,1), &wsaData);
	
	if(!nosysl) {
		openlog("matrixtunnel", LOG_PID, LOG_DAEMON);
		setlogmask(LOG_UPTO(gLogLevel));
	}
	
/*
	Initialize the MatrixSSL Library, and read in the public key (certificate)
	and private key.
*/
	if (matrixSslOpen() < 0) {
		ELOG("matrixSslOpen failed, exiting...");
		exit(1);
	}

/*
	Standard PEM files
*/
	if (matrixSslReadKeys(&keys, certfile, keyfile, NULL, NULL) < 0)  {
		ELOG("Error reading or parsing %s or %s, exiting...", 
			certfile, keyfile);
		exit(1);
	}

	// go to background
	if(!nofork) {
		daemonize();
	}

/*
	Create the listen socket
*/
	if ((srv_fd = socketListen(srv_port, &status)) == INVALID_SOCKET) {
		ELOG("Cannot listen on port %d, exiting...", srv_port);
		exit(1);
	}
/*
	Set blocking or not on the listen socket
*/
	setSocketBlock(srv_fd);

/*
	Main connection loop
*/
	struct proxyConnection	*cp=NULL;
	struct proxyConnection	*ncp;
	
	fd_set	rs, ws, es, cr;
	int			fdmax;
	struct timeval tv;
	int			res, dontClose;
	
	char		buf[4096];
	int pc, sc;
	
	int			ccount;
	
	while (!quit) {
		fdmax=srv_fd;
		ncp=NULL;
		
		FD_ZERO(&rs);
		FD_ZERO(&ws);
		FD_ZERO(&es);
		
		FD_SET(srv_fd,&rs);
		FD_SET(srv_fd,&ws);
		FD_SET(srv_fd,&es);
		ccount=0;
		
#ifndef USE_FORK
		DLOG("next select on fds: %d ",srv_fd);
		for(cp=connections;cp<&connections[MAXPROXYCOUNT];cp++) {
			if (cp->done) {
				closeProxyConnection(cp);
			}
			if (cp->secure_up) {
				FD_SET(cp->secure->fd,&rs);
				FD_SET(cp->secure->fd,&ws);
				FD_SET(cp->secure->fd,&es);

				if (fdmax < cp->secure->fd)
					fdmax = cp->secure->fd;
				
				DLOG("fd: %d",cp->secure->fd);
				ccount++;
			}
			if (cp->plain_up) {
				FD_SET(cp->plain,&rs);			
				FD_SET(cp->plain,&ws);
				FD_SET(cp->plain,&es);
					
				if (fdmax < cp->plain)
					fdmax = cp->plain;
				
				DLOG("fd: %d",cp->plain);
				ccount++;
			}
			if(!ncp && !cp->inuse){
				ncp=cp;
				memset(ncp,0,sizeof(struct proxyConnection));
			}
		}
#else
		struct proxyConnection	ncp_s;
		ncp=&ncp_s;
		memset(ncp,0,sizeof(struct proxyConnection));
#endif
		
		tv.tv_sec=10;
		tv.tv_usec=0;

		DLOG("main : select on %d open connections. fdmax: %d", ccount, fdmax);
		res=select(fdmax+1,&rs,NULL,&es,&tv);
		DLOG("select returned: %d %s", res , strerror(errno) );

		if(res<0) {
			perror("select");
			continue;
		}
		
		if(res==0)
			continue;

#ifndef USE_FORK
		// handle open connections
		for(cp=connections;cp<&connections[MAXPROXYCOUNT];cp++) {
			if (cp->secure_up && cp->plain_up) {
				if(FD_ISSET(cp->secure->fd,&es) || FD_ISSET(cp->plain,&es)) {
						closeProxyConnection(cp);
						continue;
				}
				
				if(secureReady(cp)) {
					sc=proxyReadwrite(cp,1);
					if(sc<0) {
						closeProxyConnection(cp);
						continue;
					}
				}
				
				if(plainReady(cp)) {
					pc=proxyReadwrite(cp,0);
					if(pc<0) {
						closeProxyConnection(cp);
						continue;
					}
				}
			}
		}
#endif

		// do we have new connections?
		if(FD_ISSET(srv_fd,&rs)) {
			proxyAccept(srv_fd,ncp);
		}			
	}

/*
	Close listening socket, free remaining items
*/
	socketShutdown(srv_fd);
	
#ifndef USE_FORK
	for(cp=connections;cp<&connections[MAXPROXYCOUNT];cp++) {
		closeProxyConnection(cp);
	}
#endif
	
	if(!nosysl) {
		closelog();
	}
	
	matrixSslFreeKeys(keys);
	matrixSslClose();
	WSACleanup();
	return 0;
}
Пример #5
0
// Initialize GLUT & OpenSG and start the cluster server
int main(int argc,char **argv)
{
#ifdef WIN32
	OSG::preloadSharedObject("OSGFileIO");
    OSG::preloadSharedObject("OSGImageFileIO");
	OSG::preloadSharedObject("OSGEffectGroups");
#endif
	ChangeList::setReadWriteDefault();
    osgInit(argc, argv);
	
	std::string name("ClusterServer");
    std::string connectionType("StreamSock");
    std::string address("127.0.0.1");
	bool fullscreen = true;
	bool always_on_top = false;
	bool stereo = false;
	WindowGeometry geometry = {0,0,500,500};

	if (!parseCmdLineArgs(argc, argv, name, connectionType, address, geometry, fullscreen, always_on_top, stereo))
		return 0;

	printConfiguration(name, address, connectionType, stereo, fullscreen, always_on_top);

    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE | (stereo ? GLUT_STEREO : 0));
	glutInitWindowPosition(geometry.x, geometry.y);
	glutInitWindowSize(geometry.w, geometry.h);
    int winid = glutCreateWindow(name.c_str());
    if(fullscreen) 
	{
        glutFullScreen();
    }
	if (always_on_top)
	{
		setAlwaysOnTop(name);
	}
    glutDisplayFunc(display);
    glutIdleFunc(display);
    glutReshapeFunc(reshape);
    glutSetCursor(GLUT_CURSOR_NONE);

    ract = RenderAction::create();

    window     = GLUTWindow::create();
	OSGCompat::setGlutId(window, winid);
    window->init();

	bool failed = false;
	do
	{
		try 
		{
			delete server;
			server = new ClusterServer(window, name, connectionType, address);
			server->start();
			failed = false;
		}
		catch (OSG_STDEXCEPTION_NAMESPACE::exception& e)
		{
			SLOG << "ERROR: " << e.what() << endLog;
			SLOG << "Attempting to restart ClusterServer..." << endLog;
			failed = true;
		}
	} while (failed);

    glutMainLoop();

    return 0;
}