Пример #1
0
/*===========================================================================*
 *				do_settime				     *
 *===========================================================================*/
int do_settime(struct proc * caller, message * m_ptr)
{
  clock_t newclock, ticks;
  time_t timediff;

  if (m_ptr->T_CLOCK_ID != CLOCK_REALTIME) /* only realtime can change */
	return EINVAL;

  if (m_ptr->T_SETTIME_NOW == 0) { /* user just wants to adjtime() */
	/* convert delta value from seconds and nseconds to ticks */
	ticks = (m_ptr->T_TIME_SEC * system_hz) +
				(m_ptr->T_TIME_NSEC/(1000000000/system_hz));
	set_adjtime_delta(ticks);
	return(OK);
  } /* else user wants to set the time */

  /* prevent a negative value for realtime */
  if (m_ptr->T_TIME_SEC <= boottime) {
  	/* boottime was likely wrong, try to correct it. */
	boottime = m_ptr->T_TIME_SEC;
	set_realtime(1);
	return(OK);
  }

  /* calculate the new value of realtime in ticks */
  timediff = m_ptr->T_TIME_SEC - boottime;
  newclock = (timediff*system_hz) + (m_ptr->T_TIME_NSEC/(1000000000/system_hz));

  set_realtime(newclock);

  return(OK);
}
Пример #2
0
void TimerTestFixture::testTimerUnderAttack(){

	shared_ptr<Timer> t(new Timer());
	
	set_realtime(94);
	
	for(int i = 0; i < 1000; i++){
		MWTime delay = 10000;
		
		shared_ptr <Clock> clock = Clock::instance();
		MWTime then = clock->getCurrentTimeUS();
		t->startUS(delay);
		
		while(!t->hasExpired()) clock->sleepUS(50);
		
		MWTime now = clock->getCurrentTimeUS();
		
		//cerr << "Timer fell at expiration-relative time of: " 
		//	 << (now - then) - delay << endl;
		
		CPPUNIT_ASSERT( (now - then) > delay );
		CPPUNIT_ASSERT( abs( (now - then) - delay ) < 1000 );
		
		
	}

}
Пример #3
0
void TimerTestFixture::testTimerWithTimebase(){
    
	set_realtime(94);

	shared_ptr<TimeBase> tb(new TimeBase());
	shared_ptr<Timer> t(new Timer());
	
	MWTime time_amount = 1000;
	shared_ptr<Variable> time_to_wait(new ConstantVariable(time_amount));
	StartTimer a(t,tb, time_to_wait);

	shared_ptr <Clock> clock = Clock::instance();
	MWTime then = clock->getCurrentTimeUS();
	tb->setNow();

	for(int i = 1; i < 5000; i++){
		a.execute();
		
		while(!t->hasExpired())  clock->sleepUS(10);
		MWTime now = clock->getCurrentTimeUS();
		//cerr << "Now: " << now << endl;
		
		MWTime error = (now - then) - (MWTime)(*time_to_wait);
		//cerr << "Error: " << (long long) error << endl;
		CPPUNIT_ASSERT( abs(error) < 2000 );
		CPPUNIT_ASSERT( error > 0 );
		
		time_to_wait->setValue(i * time_amount);
		
		
		//cerr << "Waiting: " << (long long)(*time_to_wait) << endl;
	}

}
static void set_mark_thread_prio(void){
#if NO_SNAPSHOT
  set_snapshot_thread_prio(0);
#else
  set_realtime(SCHED_RR,sched_get_priority_min(SCHED_RR));
#endif
}
static void set_snapshot_thread_prio(int num){
#if NO_SNAPSNOT
  bound_thread_to_cpu(NONSNAPSHOT_SNAPSHOT_CPU);
#else
  if(num==0)
    bound_thread_to_cpu(SNAPSHOT_CPU1);
  else
    bound_thread_to_cpu(SNAPSHOT_CPU2);
#endif
  set_realtime(SCHED_FIFO,audio_priority);
  //set_realtime(SCHED_FIFO,99);
}
Пример #6
0
int main(int argc, char *argv[]){
    if(argc<3){
	error("Usage: \n\t./ethtest client hostname port \n\t./ethtest server port\n\t./ethtest mvm_server port\n");
	_Exit(1);
    }
    set_realtime(0, -20);

   
    char *NBUF=getenv("NBUF");
    if(NBUF){
	nbuf=strtol(NBUF, NULL, 10);
	dbg("nbuf=%d\n", nbuf);
    }
    char *ip=0;
    if(argc>3){
	ip=argv[3];
    }
    
    if(!strcmp(argv[1], "server")){
	int port=strtol(argv[2], NULL, 10);
	listen_port(port, ip, server, 0, NULL, 1);
    }else if(!strcmp(argv[1],"mvm_server")){
	int port=strtol(argv[2], NULL, 10);
	listen_port(port, ip, mvm_server, 0, NULL, 1);
    }else{
	if(argc<4){
	    error("Usage: ./ethtest client hostname port [nrep] [nmin] [nmax] [nstep]");
	}
	const char *host=argv[2];
	int port=strtol(argv[3], NULL, 10);
	int nstep=100;
	int nmin=409584;
	int nmax=409584;
	int nrep=1000;
	if(argc>4){
	    nrep=strtol(argv[4], NULL, 10);
	}
	if(argc>5){
	    nmin=strtol(argv[5], NULL, 10);
	}
	if(argc>6){
	    nmax=strtol(argv[6], NULL, 10);
	}
	if(argc>7){
	    nstep=strtol(argv[7], NULL, 10);
	}

	client(host, port, nmin, nmax, nstep, nrep);
    }
}
Пример #7
0
/*===========================================================================*
 *				do_settime				     *
 *===========================================================================*/
int do_settime(struct proc * caller, message * m_ptr)
{
  clock_t newclock;
  int32_t ticks;
  time_t timediff, timediff_ticks;

  if (m_ptr->m_lsys_krn_sys_settime.clock_id != CLOCK_REALTIME) /* only realtime can change */
	return EINVAL;

  if (m_ptr->m_lsys_krn_sys_settime.now == 0) { /* user just wants to adjtime() */
	/* convert delta value from seconds and nseconds to ticks */
	ticks = (m_ptr->m_lsys_krn_sys_settime.sec * system_hz) +
			(m_ptr->m_lsys_krn_sys_settime.nsec/(1000000000/system_hz));
	set_adjtime_delta(ticks);
	return(OK);
  } /* else user wants to set the time */

  timediff = m_ptr->m_lsys_krn_sys_settime.sec - boottime;
  timediff_ticks = timediff * system_hz;

  /* prevent a negative value for realtime */
  if (m_ptr->m_lsys_krn_sys_settime.sec <= boottime ||
      timediff_ticks < LONG_MIN/2 || timediff_ticks > LONG_MAX/2) {
  	/* boottime was likely wrong, try to correct it. */
	boottime = m_ptr->m_lsys_krn_sys_settime.sec;
	set_realtime(1);
	return(OK);
  }

  /* calculate the new value of realtime in ticks */
  newclock = timediff_ticks +
      (m_ptr->m_lsys_krn_sys_settime.nsec/(1000000000/system_hz));

  set_realtime(newclock);

  return(OK);
}
Пример #8
0
void TimerTestFixture::testTimerOverrideMultipleTimesFast(){
	shared_ptr<Timer> t(new Timer());		

	set_realtime(94);

	for(int i = 0; i < NUM_TIMER_RESETS; i++){
		//if(i%10 == 0) {
		//	fprintf(stderr, "%d timer resets (fast)\n", i); fflush(stderr);
		//}
		
		t->startMS(10);
		
		shared_ptr <Clock> clock = Clock::instance();
		clock->sleepMS(1);
		CPPUNIT_ASSERT( t->hasExpired() == false );
		
		clock->sleepMS(6);
		
		// 3 ms left to go
		CPPUNIT_ASSERT( t->hasExpired() == false );
		
		// Bump that up to 10
		t->startMS(10);
		
		clock->sleepMS(7);
		
		// Should be 3 ms left.
		CPPUNIT_ASSERT( t->hasExpired() == false );
		
		clock->sleepMS(4);
		
		// Should be done
		CPPUNIT_ASSERT( t->hasExpired() == true );
		
		t->startMS(10);
		t->startMS(20);
		
		CPPUNIT_ASSERT( t->hasExpired() == false );
		
		clock->sleepMS(15);
		
		CPPUNIT_ASSERT( t->hasExpired() == false );
		
		clock->sleepMS(6);
		
		CPPUNIT_ASSERT( t->hasExpired() == true );
	}
}
static void busy_loop_thread(void){
  int cpu = atomic_add_get_oldval(&bl_cpu_num,1);

  bound_thread_to_cpu(cpu_nums[cpu]);
  set_realtime(SCHED_FIFO,audio_priority - 2);

  while(true){
    semaphore_wait(bl_semaphore[cpu]);
    //fprintf(stderr,"starting to busy-loop %d\n",cpu);
    while(bl_please_stop[cpu]==0){
      double start = get_ms();
      while( (get_ms() - start) < 0.01);
      //sched_yield();
    }
    //fprintf(stderr,"stopping busy-loop %d\n",cpu);
  }
}
Пример #10
0
// SangSpilling foregår ved å sette registerene A (X, Y) før en kaller opp interpreteren
int main(int argc, char **argv) {
	if((fd_mem = open("/dev/mem", O_RDWR | O_SYNC)) == -1) {
		printf("Could not get /dev/mem\n");
		return -1;
	}
	
	sid_kernel_timer = fopen("/dev/sid_timer", "r");
	if (sid_kernel_timer == NULL) {
		printf("Could not get /dev/sid_timer\n");
		return -1;
	}
	
	set_realtime();
	printWelcome();
	initGPIO();
	initPWM();

	// sjekk opp argv[1]
	if (argv[1]) {
		menu_init(argv[1]);
	} else {
		printf("Required parameter - top level directory not specified");
		exit(1);
	}
	
	if (argc > 2) {
		int z = strtol(argv[2], NULL, 10);
		printf("LCD reinit %d\n", z);
		lcd_reinit(z, z);
	} else {
		lcd_init();
	}
	
	while(1) {
		menu_run();
		
		if (inputSidFile != NULL) {
			int32_t next = c64_play();
			next = next * ((float) sh.hz / 1000000.0f);
            platform_usleep(next);
		} else {
			usleep(1000);
		}
	}
}
Пример #11
0
int main(int argc, char *argv[]){
    enum{
	P_EXE,
	P_FRAC,
	P_NSTEP,
	P_TOT,
    };
    if(argc!=P_TOT){
	info2("Usage: \n\tenv MVM_CLIENT=hostname MVM_PORT=port MVM_SASTEP=sastep ./mvm_cpu fraction nstep\n");
	_Exit(0);
    }
    int fraction=strtol(argv[P_FRAC], NULL, 10);
    int nstep=strtol(argv[P_NSTEP], NULL, 10);
    int nstep0=nstep>1?20:0;//warm up
    dmat *d_saind=dread("NFIRAOS_saind");
    const int nsa=(d_saind->nx-1)/fraction;
    int *saind=mymalloc((1+nsa),int);
    for(int i=0; i<nsa+1; i++){
	saind[i]=(int)d_saind->p[i];
    }
    dfree(d_saind);
    const int totpix=saind[nsa];
    const int nact=6981;//active subapertures.
    int ng=nsa*2;
    float FSMdelta=-0.2;
    smat *dm=snew(nact,1);
    smat *mvm=snew(nact, ng);
    smat *mtch=snew(totpix*2,1);
    smat *grad=snew(ng,1);
    smat *im0=snew(totpix,3);
    short *pix=mymalloc(totpix,short);
    short *pixbias=mymalloc(totpix,short);
    {
	rand_t rseed;
	seed_rand(&rseed, 1);
	srandu(mvm, 1e-7, &rseed);
	srandu(mtch, 1, &rseed);
	for(int i=0; i<totpix; i++){
	    pix[i]=(short)(randu(&rseed)*25565);
	    pixbias[i]=(short)(randu(&rseed)*1000);
	}
    }
    smat *mvmt=strans(mvm);
    int sastep=200;//how many subapertures each time
    int nrep=1;
    if(getenv("MVM_NREP")){
	nrep=strtol(getenv("MVM_NREP"), NULL, 10);
    }
    if(getenv("MVM_SECT")){
	sastep=nsa/strtol(getenv("MVM_SECT"), NULL, 10);
    }
    if(getenv("MVM_TRANS")){
	use_trans=strtol(getenv("MVM_TRANS"), NULL, 10);
    }
    if(getenv("MVM_SASTEP")){
	sastep=strtol(getenv("MVM_SASTEP"), NULL, 10);
    }
    info2("use_trans=%d, nrep=%d, sastep=%d\n", use_trans, nrep, sastep);
    int sock=-1;
    char* MVM_CLIENT=getenv("MVM_CLIENT");
    if(MVM_CLIENT){
	short port=(short)strtol(getenv("MVM_PORT"), NULL, 10);
	sock=connect_port(MVM_CLIENT, port, 0 ,1);
	if(sock!=-1) {
	    info2("Connected\n");
	    int cmd[7];
	    cmd[0]=nact;
	    cmd[1]=nsa;
	    cmd[2]=sastep;
	    cmd[3]=totpix;
	    cmd[4]=nstep;
	    cmd[5]=nstep0;
	    cmd[6]=2;
	    if(stwriteintarr(sock, cmd, 7) 
	       || stwriteintarr(sock, saind, nsa+1)
	       || stwrite(sock, pix, sizeof(short)*totpix)){
		close(sock); sock=-1;
		warning("Failed: %s\n", strerror(errno));
	    }
	}
    }
    int ready=0;
    if(sock!=-1 && stwriteint(sock, ready)){
	warning("error send ready signal: %s\n", strerror(errno));
	close(sock); sock=-1;
    }
    smat *timing=snew(nstep, 1);
    TIC;
    float timtot=0, timmax=0, timmin=INFINITY;
    set_realtime(-1, -20);
    for(int jstep=-nstep0; jstep<nstep; jstep++){
	int istep=jstep<0?0:jstep;
	tic;
	double theta=M_PI*0.5*istep+FSMdelta;
	float cd=cos(theta);
	float sd=cos(theta);
	szero(dm);
	for(int isa=0; isa<nsa; isa+=sastep){
	    int npixleft;
	    int nsaleft;
	    if(nsa<isa+sastep){//terminate
		npixleft=totpix-saind[isa];
		nsaleft=nsa-isa;
	    }else{
		npixleft=saind[isa+sastep]-saind[isa];
		nsaleft=sastep;
	    }

	    short *pcur=pix+saind[isa];
	    if(sock!=-1){
		if(stread(sock, pcur, sizeof(short)*npixleft)){
		    warning("failed: %s\n", strerror(errno));
		    close(sock); sock=-1;
		    _Exit(1);
		}
		if(isa==0) tic;
	    }
	    //Matched filter
	    mtch_do(mtch->p, pix, pixbias, 
		    grad->p+isa*2, im0->p, im0->p+totpix, im0->p+totpix*2,
		    saind+isa, nsaleft, cd, sd);
	    //MVM
	    for(int irep=0; irep<nrep; irep++){
		if(use_trans){
		    mvmt_do(mvmt->p+isa*2, grad->p+isa*2,dm->p, nact, nsaleft*2, ng);
		}else{
		    mvm_do(mvm->p+isa*2*nact, grad->p+isa*2, dm->p, nact, nsaleft*2);
		}
	    }
	}//for isa
	if(sock!=-1){
	    if(stwrite(sock, dm->p, sizeof(float)*nact)){
		warning("error write dmres: %s\n", strerror(errno));
		close(sock); sock=-1;
		_Exit(1);
	    }
	    if(streadint(sock, &ready)){//acknowledgement.
		warning("error read ack failed: %s\n", strerror(errno));
		close(sock), sock=-1;
		_Exit(1);
	    }
	    timing->p[istep]=ready*1.e-6;
	}else{
	    timing->p[istep]=toc3;//do not tic.
	}
	if(jstep==istep){
	    timtot+=timing->p[istep];
	    if(timmax<timing->p[istep]){
		timmax=timing->p[istep];
	    }
	    if(timmin>timing->p[istep]){
		timmin=timing->p[istep];
	    }
	}
    }//for istep
    float timmean=timtot/nstep;
    info2("Timing is mean %.3f, max %.3f min %.3f. BW is %.1f of 51.2GB/s\n",
	  timmean*1e3, timmax*1e3, timmin*1e3, nrep*(nact*ng+nact+ng)*sizeof(float)/timmean/(1024*1024*1024));
    writebin(timing, "cpu_timing_%s", HOST);
    if(nstep==1){
	writearr("cpu_pix", 1, sizeof(short), M_INT16, NULL, pix, totpix, 1);
	writearr("cpu_pixbias", 1, sizeof(short), M_INT16, NULL, pixbias, totpix, 1);
	writebin(dm, "cpu_dm");
	writebin(grad, "cpu_grad");
	writebin(mvm, "cpu_mvm");
	writebin(mtch, "cpu_mtch");
    }
   
}
Пример #12
0
/* Change priority for thread 'threadhandle', or for the calling thread if 'threadhandle' == NULL.
 * threadhandle == 0x1 means "Main Psychtoolbox thread" and may incur special treatment.
 * 'basePriority' can be 0 for normal scheduling, 1 for higher priority and 2 for highest priority.
 * 'tweakPriority' modulates more fine-grained within the category given by 'basepriority'. It
 * can be anywhere between 0 and some big value where bigger means more priority.
 *
 * Returns zero on success, non-zero on failure to set new priority.
 */
int PsychSetThreadPriority(psych_thread* threadhandle, int basePriority, int tweakPriority)
{
	int							rc = 0;
	pthread_t					thread;
    int							kernError;
    task_t						threadID;
    thread_policy_t				threadPolicy;
    mach_msg_type_number_t		policyCount, policyCountFilled;
    boolean_t					isDefault;
	
	if ((NULL != threadhandle) && ((psych_thread*) 0x1 != threadhandle)) {
		// Retrieve thread handle of thread to change:
		thread = *threadhandle;
	}
	else {
		// Retrieve handle of calling thread:
		thread = pthread_self();
	}

	// Map Posix thread handle to Mach thread handle:
	threadID = pthread_mach_thread_np(thread);

	// Get timebase:
	double ticksPerSec = PsychGetKernelTimebaseFrequencyHz();
	double baseQuantum = 0.010;
	
	// tweakPriority <= 0 -> 10% cpu. Can go up to 90% at level >=8 in 10% increments.
	if (tweakPriority < 0) tweakPriority = 0;
	if (tweakPriority > 8) tweakPriority = 8;
	
	switch(basePriority) {
		case 0:	// Normal priority: Drop to standard scheduling.
			threadPolicy = (thread_policy_t) malloc(sizeof(thread_standard_policy_data_t));
			policyCount  = THREAD_STANDARD_POLICY_COUNT;
			policyCountFilled = policyCount;
			isDefault = TRUE;
			kernError = thread_policy_get(threadID, THREAD_STANDARD_POLICY, threadPolicy, &policyCountFilled, &isDefault);
			if (kernError == 0) kernError = thread_policy_set(threadID, THREAD_STANDARD_POLICY, threadPolicy, policyCountFilled);
			free(threadPolicy);
			rc = (int) kernError;
		break;
		
		case 1: // High priority: Up to 90% cpu utilization, but preemptible for urgent tasks, with an allowable total time to completion of baseQuantum.
			// This basically says: "I am more important than bog-standard threads, and i want to have x msecs of 10 msecs very 10 msecs, but i don't care
			// about startup delay (reaction times) or interruptions, as long as i don't lose more than 10 msecs. Good for high priority compute tasks
			// with lots of wiggle room wrt. when stuff happens, e.g., some data producer thread or i/o thread which needs to deliver/handle a certain
			// amount of data processing/shuffling/io within a certain time quantum, because it is feeding some other realtime thread or hw process,
			// due to things like intermediate fifo buffering, itself can tolerate a certain lag.
			// This may become useful in the future for i/o functions in IOPort/PsychHID, movie playback/recording helper threads etc...
			rc = set_realtime(threadID, baseQuantum * ticksPerSec, (((double) tweakPriority + 1) / 10) * baseQuantum * ticksPerSec, baseQuantum * ticksPerSec, TRUE);
		break;
		
		case 2: // Realtime priority: Up to (tweakPriority + 1) msecs out of 10 msecs of *uninterrupted* computation (non-preemptible after start).
			// However, after the thread becomes runnable, its actual start of uninterrupted execution can be delayed by up to 1 msec, e.g., if more
			// important (basePriority 10) threads are executing, or a high priority or lower priority thread needs some computation time.
			// This is our most common use-case: Most of our realtime threads are completely triggered (= reactive to) by external hardware input events.
			// They wait on the arrival of some external event, e.g., a user key press or mouse click, some trigger signal from some I/O device like
			// response box, serial port or parallel port, DAQ board etc., or for some timer going off at a certain time. Most often they have to respond
			// to some trigger event by either executing some action, or by simply timestamping the event, like a button press of a subject, or some TTL
			// trigger from some equipment. Executing the actual action, or timestamping, or storing the received data in some queue, is usually fast,
			// the computation finishes quickly. As timestamping or external hardware control can be involved, we don't want to get preempted once running,
			// to avoid impairing precision of timestamps or clock-sync algorithms or hw control actions. However for typical neuro-science experiments,
			// we can tolerate a random time delay (or imprecision in acquired timestamps) of 1 msec.
			// Typical consumers of this setup: IOPort, PsychHID, Movie playback or video capture high-level control.
			rc = set_realtime(threadID, baseQuantum * ticksPerSec, (((double) tweakPriority + 1) / 10) * baseQuantum * ticksPerSec, (((double) tweakPriority + 1 + 1) / 10) * baseQuantum * ticksPerSec, FALSE);
		break;

		case 10:  // Critical priority: Up to (tweakPriority + 1) msecs out of 10 msecs of *uninterrupted* computation (non-preemptible after start),
			// must run as soon as possible and then complete without distraction. This is good for timestamping operations that must not be interrupted
			// in the wrong moment, because that would impair timestamps significantly, and for time-based triggering of execution of operations with
			// the highest possible timing precision.
			// Out main client of this is currently the OpenGL flipperThread used by Screen for async flip scheduling and timestamping, and for
			// frame-sequential stereo fallback. For those apps, uninterrupted low latency is crucial. flipperThread uses tweakPriority == 2, so could
			// run for up to 3 msecs uninterrupted, something it usually won't do (closer to << 1 msec is expected), but can do in a worst case scenario,
			// where various workarounds for broken GPU drivers are active and screen resolution/refresh rate settings are especially suboptimal.
			// The other client is video refresh rate calibration during Screen('GetFlipInterval') active calibration or during Screen('Openwindow')
			// default calibration.
			//
			// Future clients may be found in the IOPort async-task framework for highly timing sensitive i/o operations.
			rc = set_realtime(threadID, baseQuantum * ticksPerSec, (((double) tweakPriority + 1) / 10) * baseQuantum * ticksPerSec, 0, FALSE);
		break;

		default:
			printf("PTB-CRITICAL: In call to PsychSetThreadPriority(): Invalid/Unknown basePriority %i provided!\n", basePriority);
			rc = 2;
	}

	// Try to apply new priority and scheduling method:
	if (rc != 0) {
		printf("PTB-WARNING: In call to PsychSetThreadPriority(): Failed to set new basePriority %i, tweakPriority %i, effective %i [%s] for thread %p provided!\n",
				basePriority, tweakPriority, tweakPriority, (basePriority > 0) ? "REALTIME" : "NORMAL", (void*) threadhandle);
		printf("PTB-WARNING: This can lead to timing glitches and odd performance behaviour.\n");
	}

	// rc is either zero for success, or 2 for invalid arg, or some other non-zero failure code:
	return(rc);
}
static void set_free_thread_prio(void){
  set_realtime(SCHED_FIFO,
               audio_priority >= 2
               ? GC_MAX(sched_get_priority_min(SCHED_FIFO),audio_priority-1)
               : audio_priority);
}
Пример #14
0

void StandardStateSystem::run() {
#ifdef __APPLE__
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
#endif
	
	weak_ptr<State> next_state;


	int bus_speed, mib [2] = { CTL_HW, HW_BUS_FREQ };
	size_t len;   
	len = sizeof (bus_speed);
	sysctl (mib, 2, &bus_speed, &len, NULL, 0);
	
	int didit = set_realtime(STATE_SYSTEM_PRIORITY);
	
	if(didit){
		//fprintf(stderr,"Scheduler went realtime.  Rock on.\n");
		//fflush(stderr);
	} else {
		fprintf(stderr,"Scheduler didn't go realtime.  Bummer.\n");
		fflush(stderr);
	}

    // Make a copy of the experiment to ensure that it isn't destroyed before we're done with it
    shared_ptr<Experiment> current_experiment = GlobalCurrentExperiment;
    if (!current_experiment) {
        merror(M_STATE_SYSTEM_MESSAGE_DOMAIN,
               "Cannot start state system without a valid experiment defined");
        return;
Пример #15
0
int main(int argc, const char **argv)
{
	pthread_mutexattr_t ma;
	pthread_mutex_t *mutex;
	int fd, ret, i;
	pid_t pid;
	void *addr;
	int num_children;
	int priority = PRIO_NORMAL;

	if (argc < 3 || argc > 4) {
		fprintf(stderr, "Usage: %s <file> <n> [0|1|2]\n", argv[0]);
		fprintf(stderr, "       %s <file> debug\n", argv[0]);
		exit(1);
	}

	if (argc == 4) {
		priority = atoi(argv[3]);
	}

	if (priority == PRIO_REALTIME) {
		set_realtime();
	} else if (priority == PRIO_NICE_20) {
		high_priority();
	}

	fd = open(argv[1], O_CREAT|O_RDWR, 0600);
	if (fd == -1) {
		fprintf(stderr, "open failed\n");
		exit(1);
	}

	ret = lseek(fd, 0, SEEK_SET);
	if (ret != 0) {
		fprintf(stderr, "lseek failed\n");
		exit(1);
	}

	ret = ftruncate(fd, sizeof(pthread_mutex_t));
	if (ret != 0) {
		fprintf(stderr, "ftruncate failed\n");
		exit(1);
	}

	addr = mmap(NULL, sizeof(pthread_mutex_t), PROT_READ|PROT_WRITE,
		    MAP_SHARED|MAP_FILE, fd, 0);
	if (addr == NULL) {
		fprintf(stderr, "mmap failed\n");
		exit(1);
	}

	mutex = (pthread_mutex_t *)addr;

	if (strcmp(argv[2], "debug") == 0) {
		ret = pthread_mutex_trylock(mutex);
		if (ret == EOWNERDEAD) {
			ret = pthread_mutex_consistent(mutex);
			if (ret == 0) {
				pthread_mutex_unlock(mutex);
			}
		} else if (ret == EBUSY) {
			printf("pid=%u\n", mutex->__data.__owner);
		} else if (ret == 0) {
			pthread_mutex_unlock(mutex);
		}
		exit(0);
	}

	ret = pthread_mutexattr_init(&ma);
	if (ret != 0) {
		fprintf(stderr, "pthread_mutexattr_init failed\n");
		exit(1);
	}

	ret = pthread_mutexattr_settype(&ma, PTHREAD_MUTEX_ERRORCHECK);
	if (ret != 0) {
		fprintf(stderr, "pthread_mutexattr_settype failed\n");
		exit(1);
	}

	ret = pthread_mutexattr_setpshared(&ma, PTHREAD_PROCESS_SHARED);
	if (ret != 0) {
		fprintf(stderr, "pthread_mutexattr_setpshared failed\n");
		exit(1);
	}

	ret = pthread_mutexattr_setrobust(&ma, PTHREAD_MUTEX_ROBUST);
	if (ret != 0) {
		fprintf(stderr, "pthread_mutexattr_setrobust failed\n");
		exit(1);
	}

	ret = pthread_mutex_init(mutex, &ma);
	if (ret != 0) {
		fprintf(stderr, "pthread_mutex_init failed\n");
		exit(1);
	}

	ret = pthread_mutex_lock(mutex);
	if (ret != 0) {
		fprintf(stderr, "pthread_mutex_lock failed\n");
		exit(1);
	}

	setpgid(0, 0);

	fprintf(stderr, "Creating children\n");
	num_children = atoi(argv[2]);

	for (i=0; i<num_children; i++) {
		pid = fork();
		if (pid < 0) {
			fprintf(stderr, "fork() failed\n");
			exit(1);
		}
		if (pid == 0) {
			close(fd);
			run_child(argv[1]);
			exit(1);
		}
	}

	fprintf(stderr, "Waiting for children\n");

	ret = pthread_mutex_unlock(mutex);
	if (ret != 0) {
		fprintf(stderr, "pthread_mutex_unlock failed\n");
		exit(1);
	}

	for (i=0; i<num_children; i++) {
		int status;

		pid = waitpid(-1, &status, 0);
		if (pid <= 0) {
			fprintf(stderr, "waitpid() failed\n");
		}
	}

	close(fd);
	unlink(argv[1]);
	exit(0);
}
static  void set_priority(priority_t *priority){
  set_realtime(priority->policy,priority->priority);
}
int main(int ac, char **av)
{
    int             realtime = 0;
    int		    parallel = 1;
    int             warmup = 0;
    int             repetitions = -1;
    int             c;
    char            buf[512];
    timer_e	    what = USLEEP;
    state_t         state;
    char           *scheduler = "";
    char           *mechanism = "usleep";
    char           *usage = "[-r] [-u <method>] [-P <parallelism>] [-W <warmup>] [-N <repetitions>] usecs\nmethod=usleep|nanosleep|select|pselect|itimer\n";

    realtime = 0;

    while ((c = getopt(ac, av, "ru:W:N:")) != EOF) {
	switch (c) {
	case 'r':
	    realtime = 1;
	    break;
	case 'u':
	    if (strcmp(optarg, "usleep") == 0) {
		what = USLEEP;
		mechanism = "usleep";
	    } else if (strcmp(optarg, "nanosleep") == 0) {
		what = NANOSLEEP;
		mechanism = "nanosleep";
	    } else if (strcmp(optarg, "select") == 0) {
		what = SELECT;
		mechanism = "select";
#ifdef _POSIX_SELECT
	    } else if (strcmp(optarg, "pselect") == 0) {
		what = PSELECT;
		mechanism = "pselect";
#endif /* _POSIX_SELECT */
	    } else if (strcmp(optarg, "itimer") == 0) {
		what = ITIMER;
		mechanism = "itimer";
	    } else {
		lmbench_usage(ac, av, usage);
	    }
	    break;
	case 'P':
	    parallel = atoi(optarg);
	    if (parallel <= 0) lmbench_usage(ac, av, usage);
	    break;
	case 'W':
	    warmup = atoi(optarg);
	    break;
	case 'N':
	    repetitions = atoi(optarg);
	    break;
	default:
	    lmbench_usage(ac, av, usage);
	    break;
	}
    }
    if (optind != ac - 1) {
	lmbench_usage(ac, av, usage);
    }

    state.usecs = bytes(av[optind]);
    if (realtime && set_realtime()) scheduler = "realtime ";

    switch (what) {
    case USLEEP:
	benchmp(NULL, bench_usleep, NULL, 
		0, parallel, warmup, repetitions, &state);
	break;
    case NANOSLEEP:
	benchmp(NULL, bench_nanosleep, NULL, 
		0, parallel, warmup, repetitions, &state);
	break;
    case SELECT:
	benchmp(NULL, bench_select, NULL, 
		0, parallel, warmup, repetitions, &state);
	break;
#ifdef _POSIX_SELECT
    case PSELECT:
	benchmp(NULL, bench_pselect, NULL, 
		0, parallel, warmup, repetitions, &state);
	break;
#endif /* _POSIX_SELECT */
    case ITIMER:
	benchmp(initialize, bench_itimer, NULL, 
		0, parallel, warmup, repetitions, &state);
	break;
    default:
	lmbench_usage(ac, av, usage);
	break;
    }
    sprintf(buf, "%s%s %lu microseconds", scheduler, mechanism, state.usecs);
    micro(buf, get_n());
    return (0);
}
Пример #18
0
int disk_scan(disk_t *disk, enum scan_mode mode, unsigned data_size)
{
	disk->run = 1;
	void *data = allocate_buffer(data_size);
	uint32_t *scan_order = NULL;
	int result = 0;
	struct scan_state state = {.latency = NULL, .progress_bytes = 0, .progress_full = 1000};
	struct timespec ts_start;
	struct timespec ts_end;
	time_t scan_time;

	disk->conclusion = CONCLUSION_SCAN_PROBLEM;

	if (data_size % disk->sector_size != 0) {
		data_size -= data_size % disk->sector_size;
		if (data_size == 0)
			data_size = disk->sector_size;
		ERROR("Cannot scan data not in multiples of the sector size, adjusted scan size to %u", data_size);
	}

	set_realtime(true);
	clock_gettime(CLOCK_MONOTONIC, &ts_start);

	INFO("Scanning disk %s in %u byte steps", disk->path, data_size);
	scan_time = time(NULL);
	INFO("Scan started at: %s", ctime(&scan_time));
	VVVERBOSE("Using buffer of size %d", data_size);

	if (data == NULL) {
		ERROR("Failed to allocate data buffer, errno=%d: %s", errno, strerror(errno));
		result = 1;
		goto Exit;
	}

	uint64_t offset;
	const uint64_t disk_size_bytes = disk->num_bytes;
	const uint64_t latency_stride = calc_latency_stride(disk);
	VVERBOSE("latency stride is %"PRIu64, latency_stride);

	state.latency_bucket = 0;
	state.latency_stride = latency_stride;
	state.latency_count = 0;
	state.latency = malloc(sizeof(uint32_t) * latency_stride);
	state.data = data;

	scan_order = calc_scan_order(disk, mode, latency_stride, data_size);
	if (!scan_order) {
		result = 1;
		ERROR("Failed to generate scan order");
		goto Exit;
	}

	verbose_extra_newline = 1;
	for (offset = 0; disk->run && offset < disk_size_bytes; offset += latency_stride * disk->sector_size) {
		VERBOSE("Scanning stride starting at %"PRIu64" done %"PRIu64"%%", offset, offset*100/disk_size_bytes);
		progress_calc(disk, &state, 0);
		latency_bucket_prepare(disk, &state, offset);
		if (!disk_scan_latency_stride(disk, &state, offset, data_size, scan_order))
			break;
		latency_bucket_finish(disk, &state, offset + latency_stride * disk->sector_size);

		if (disk->is_ata)
			disk_ata_monitor(disk);
		else
			disk_scsi_monitor(disk);
	}
	verbose_extra_newline = 0;

	if (!disk->run) {
		INFO("Disk scan interrupted");
		disk->conclusion = CONCLUSION_ABORTED;
	} else {
		disk->conclusion = conclusion_calc(disk);
	}
	report_scan_done(disk);

Exit:
	clock_gettime(CLOCK_MONOTONIC, &ts_end);
	set_realtime(false);
	free(scan_order);
	free_buffer(data, data_size);
	free(state.latency);
	disk->run = 0;
	scan_time = time(NULL);
	INFO("Scan ended at: %s", ctime(&scan_time));
	INFO("Scan took %d second", (int)(ts_end.tv_sec - ts_start.tv_sec));
	return result;
}
Пример #19
0
void *zenScheduledExecutionThread(void *arglist){
	
	
	// Hand-off the task description
	shared_ptr<ZenScheduleTask> *task_ptr = (shared_ptr<ZenScheduleTask> *)arglist;
	shared_ptr<ZenScheduleTask> task = *task_ptr;
	delete task_ptr;	// moved until end for speediness
	
	//task->heartbeat();
	if(VERBOSE_SCHEDULER) mprintf("Scheduled thread spawned %p", task.get());
	
	
	// Unpack the task description
	boost::function<void *()> functor = task->getFunctor();
	int ntimes = task->getNTimes();
	MWTime initial_delay_us = task->getInitialDelayUS();
	MWTime repeat_interval_us = task->getRepeatIntervalUS();
	if(VERBOSE_SCHEDULER) mprintf(" ****** repeat_interval_us = %lu   %p", (unsigned long)repeat_interval_us, task.get());
	
	MWTime start_time_us = task->getStartTimeUS();
	MissedExecutionBehavior behavior = task->getMissedExecutionBehavior();
	int priority = task->getPriority();
	MWTime warning_slop_us = task->getWarningSlopUS();
	int fail_slop_us = task->getFailureSlopUS();
	MWTime computation_time_us = task->getComputationTimeUS();
	
	
	
	MWTime next_us;
	long ndone = 0;
	
	// Go realtime, if requested
	if(VERBOSE_SCHEDULER) mprintf("Computation time = %lld", computation_time_us);
	if(computation_time_us > 0LL){
		//#if (defined(__ppc__) && defined(__APPLE__))
		//mprintf("%d", get_bus_speed);
		
#ifndef	LOW_PRIORITY_MODE
		set_realtime(((double)get_bus_speed() * (double)repeat_interval_us) / 1000000.0, 
					 ((double)get_bus_speed() * (double)computation_time_us) / 1000000.0,  
					 ((double)get_bus_speed() * (double)repeat_interval_us) / 1000000.0);
#endif
		//#endif
	} else {
#if REALTIME_SCHEDULER
		
#ifndef	LOW_PRIORITY_MODE
		int didit = set_realtime(priority);
		if(didit){
			//fprintf(stderr, "Scheduler went realtime.  Rock on.\n");
			//fflush(stderr);
		} else {
			fprintf(stderr,"Scheduler didn't go realtime.  Bummer.\n");
			fflush(stderr);
		}
#endif
#endif
	}
	
	
	MWTime now_us = task->getScheduler()->getClock()->getCurrentTimeUS();
	
	//cerr << "Startup latency: " << now_us - start_time_us << endl;
	
	MWTime time_to_first_shot = (start_time_us + initial_delay_us) - now_us;
	// Sleep if there is an initial delay
	if(time_to_first_shot > 0){		
		task->getScheduler()->getClock()->sleepUS(time_to_first_shot);
	}
	
	
	// Compute the next scheduled execution time
	next_us = start_time_us + initial_delay_us + repeat_interval_us;
	
	
	
	if(VERBOSE_SCHEDULER) 
		mprintf("Scheduled thread entering main loop (%ld done, %d total)  %p",
				ndone, ntimes, task.get());
	
	
	while(task->isActive() && 
		  (ntimes == M_REPEAT_INDEFINITELY || ndone < ntimes)){
		
		
		//task->heartbeat();
		
		// *********************
		// Execute the payload
		// *********************
		
		if(VERBOSE_SCHEDULER){
			mprintf("Scheduled function called "
					"(main loop, %ld done / %d total) %p",
					ndone, ntimes, task.get());
		}
		
		now_us = task->getScheduler()->getClock()->getCurrentTimeUS();		
		functor();
		
		if(VERBOSE_SCHEDULER){ 
			mprintf("Scheduled function returned "
					"(main loop) %p", task.get());
		}
		
		
		
		if(fail_slop_us > (MWTime)0 &&
		   now_us - next_us > fail_slop_us){
			if(!SILENCE_SCHEDULE_WARNINGS){
				merror(M_SCHEDULER_MESSAGE_DOMAIN,
					   "Scheduled task (%s) not on time (off by %lld; task = %p; priority= %d)",
					   task->getDescription().c_str(),
					   now_us - next_us, 
					   task.get(), 
					   task->getPriority());
			}
			
		} else if(warning_slop_us > (MWTime)0 &&
				  now_us - next_us > warning_slop_us){
			if (!SILENCE_SCHEDULE_WARNINGS) {
				mwarning(M_SCHEDULER_MESSAGE_DOMAIN,
						 "Scheduled task (%s) not on time (off by %lld; task = %p; priority=%d)", 
						 task->getDescription().c_str(),
						 now_us - next_us, task.get(),
						 task->getPriority());
			}
		}
		
		
		// one closer to being done...
		ndone++;
		
		// communicate back with the task object
		task->setNDone(ndone);
		
		if(ntimes != M_REPEAT_INDEFINITELY && ndone >= ntimes){
			if(VERBOSE_SCHEDULER) 
				mprintf("Scheduled task has completed %ld executions, quitting  %p",
						ndone, task.get());
			break;
		}
		
		if(!task->isActive()){
			if(VERBOSE_SCHEDULER) 
				mprintf("Scheduled execution deactivated (2) %p", task.get());
			
			break;
		}
		
		// this is when the next one should happen
		next_us = start_time_us + initial_delay_us + (ndone)*repeat_interval_us;		
		
		now_us = task->getScheduler()->getClock()->getCurrentTimeUS();
		
		// are we going too slow?
		
		//	if (warned) mprintf("DROP decision values: now: %d   next: %d   now-next:  %d ms  repeat interval %d ms",
		//		(long)(now_us/1000), (long)(next_us/1000), (long)((now_us - next_us)/1000), (long)(repeat_interval_us/1000));
		
		// JJD change Jan 30, 2007.
		// if when the NEXT one should happen is already more than the repeat_interval behind, then we are already too late!
		// This is partly how we can get into the state with a bunch of warnings, but no correction by dropping.
		// If warnings are less than this, then it IS proper behavior to keep spitting out the warnings -- it is up to the person scheduling 
		// things to set the warning level appropriately (i.e. greater than the repeat interval plus some slop to deal with delays inside this routine).
		
		//if((now_us - next_us) > (repeat_interval_us + warning_slop_us)) {		// DDC old test 
		if((now_us - next_us) > (repeat_interval_us)) {							// JJD new test Jan 30, 2007
																				//if (now_us > next_us) {							// DDC Feb 12, 3007
			
			if(VERBOSE_SCHEDULER){
				mprintf("Thread not keeping up (off by %ld usec: now = %lu, next = %lu repeat = %lu; priority = %d)  %p",
						(long)(now_us - next_us),
						(unsigned long)now_us, 
						(unsigned long)next_us, 
						(unsigned long)repeat_interval_us, 
						priority,
						task.get());
			}
			
			
			switch(behavior){
				
				case M_MISSED_EXECUTION_DROP:
					if(repeat_interval_us){
						if(VERBOSE_SCHEDULER) 
							mprintf("Dropping (ndone was: %ld)  %p", ndone, task.get());
						ndone += 0 + 
							(int)((now_us - next_us) / repeat_interval_us);
						//mprintf("((now_us - next_us) / repeat_interval_us) = %lld", ((now_us - next_us) / repeat_interval_us));	
						// move on
						if(warning_slop_us > (MWTime)0){
							if (!SILENCE_SCHEDULE_WARNINGS){
								mwarning(M_SCHEDULER_MESSAGE_DOMAIN,
										 "Scheduled task (%s) falling behind, dropping %d "
										 "scheduled executions "
										 "(priority = %d, interval = %lld, task = %p)",
										 task->getDescription().c_str(),
										 1 + (int)((now_us - next_us) /
												   repeat_interval_us),
										 priority, 
										 repeat_interval_us,
										 task.get());
								
								//lastWarnTimeUS = now_us;	
								
								if(task.get() == NULL){
									merror(M_SCHEDULER_MESSAGE_DOMAIN,
										   "NULL task: something is very wrong");
								}
							}
						}
					}
					break; 
					
				case M_MISSED_EXECUTION_CATCH_UP:
					// go go go....
					continue;
					
				case M_MISSED_EXECUTION_FAIL:
					merror(M_SCHEDULER_MESSAGE_DOMAIN,
						   "Scheduled execution failed to keep up");
					// TODO: put on the brakes
					break;
			}
																				} 
		
		
		next_us = start_time_us + initial_delay_us + 
			((MWTime)(ndone))*repeat_interval_us;
		
		if((next_us - now_us) > 0){
			if(VERBOSE_SCHEDULER) 
				mprintf("Scheduled thread sleeping... (2: %lld) %p", 
						(next_us - now_us), task.get());
			task->getScheduler()->getClock()->sleepUS(next_us - now_us);
		}
	}
	
	
	task->getScheduler()->removeTask(task->getNodeID());
	
	
	if(VERBOSE_SCHEDULER) mprintf("Scheduled thread ending... %p", task.get());
	return 0;
	
}