Esempio n. 1
0
static void
init_private(void)
{
	struct rlimit rlim;
	size_t len;
	int mib[2];
	char *env, *env_bigstack, *env_splitstack;

	_thr_umutex_init(&_mutex_static_lock);
	_thr_umutex_init(&_cond_static_lock);
	_thr_umutex_init(&_rwlock_static_lock);
	_thr_umutex_init(&_keytable_lock);
	_thr_urwlock_init(&_thr_atfork_lock);
	_thr_umutex_init(&_thr_event_lock);
	_thr_umutex_init(&_suspend_all_lock);
	_thr_once_init();
	_thr_spinlock_init();
	_thr_list_init();
	_thr_wake_addr_init();
	_sleepq_init();
	_single_thread = NULL;
	_suspend_all_waiters = 0;

	/*
	 * Avoid reinitializing some things if they don't need to be,
	 * e.g. after a fork().
	 */
	if (init_once == 0) {
		/* Find the stack top */
		mib[0] = CTL_KERN;
		mib[1] = KERN_USRSTACK;
		len = sizeof (_usrstack);
		if (sysctl(mib, 2, &_usrstack, &len, NULL, 0) == -1)
			PANIC("Cannot get kern.usrstack from sysctl");
		env_bigstack = getenv("LIBPTHREAD_BIGSTACK_MAIN");
		env_splitstack = getenv("LIBPTHREAD_SPLITSTACK_MAIN");
		if (env_bigstack != NULL || env_splitstack == NULL) {
			if (getrlimit(RLIMIT_STACK, &rlim) == -1)
				PANIC("Cannot get stack rlimit");
			_thr_stack_initial = rlim.rlim_cur;
		}
		len = sizeof(_thr_is_smp);
		sysctlbyname("kern.smp.cpus", &_thr_is_smp, &len, NULL, 0);
		_thr_is_smp = (_thr_is_smp > 1);
		_thr_page_size = getpagesize();
		_thr_guard_default = _thr_page_size;
		_pthread_attr_default.guardsize_attr = _thr_guard_default;
		_pthread_attr_default.stacksize_attr = _thr_stack_default;
		env = getenv("LIBPTHREAD_SPINLOOPS");
		if (env)
			_thr_spinloops = atoi(env);
		env = getenv("LIBPTHREAD_YIELDLOOPS");
		if (env)
			_thr_yieldloops = atoi(env);
		env = getenv("LIBPTHREAD_QUEUE_FIFO");
		if (env)
			_thr_queuefifo = atoi(env);
		TAILQ_INIT(&_thr_atfork_list);
	}
	init_once = 1;
}
Esempio n. 2
0
/* 3. mark types that use vlen*/
static void
processtypes(void)
{
    int i,j,keep,added;
    List* sorted = listnew(); /* hold re-ordered type set*/
    /* Prime the walk by capturing the set*/
    /*     of types that are dependent on primitive types*/
    /*     e.g. uint vlen(*) or primitive types*/
    for(i=0;i<listlength(typdefs);i++) {
        Symbol* sym = (Symbol*)listget(typdefs,i);
	keep=0;
	switch (sym->subclass) {
	case NC_PRIM: /*ignore pre-defined primitive types*/
	    sym->touched=1;
	    break;
	case NC_OPAQUE:
	case NC_ENUM:
	    keep=1;
	    break;
        case NC_VLEN: /* keep if its basetype is primitive*/
	    if(sym->typ.basetype->subclass == NC_PRIM) keep=1;
	    break;	    	
	case NC_COMPOUND: /* keep if all fields are primitive*/
	    keep=1; /*assume all fields are primitive*/
	    for(j=0;j<listlength(sym->subnodes);j++) {
		Symbol* field = (Symbol*)listget(sym->subnodes,j);
		ASSERT(field->subclass == NC_FIELD);
		if(field->typ.basetype->subclass != NC_PRIM) {keep=0;break;}
	    }	  
	    break;
	default: break;/* ignore*/
	}
	if(keep) {
	    sym->touched = 1;
	    listpush(sorted,(void*)sym);
	}
    }	
    /* 2. repeated walk to collect level i types*/
    do {
        added=0;
        for(i=0;i<listlength(typdefs);i++) {
	    Symbol* sym = (Symbol*)listget(typdefs,i);
	    if(sym->touched) continue; /* ignore already processed types*/
	    keep=0; /* assume not addable yet.*/
	    switch (sym->subclass) {
	    case NC_PRIM: 
	    case NC_OPAQUE:
	    case NC_ENUM:
		PANIC("type re-touched"); /* should never happen*/
	        break;
            case NC_VLEN: /* keep if its basetype is already processed*/
	        if(sym->typ.basetype->touched) keep=1;
	        break;	    	
	    case NC_COMPOUND: /* keep if all fields are processed*/
	        keep=1; /*assume all fields are touched*/
	        for(j=0;j<listlength(sym->subnodes);j++) {
		    Symbol* field = (Symbol*)listget(sym->subnodes,j);
		    ASSERT(field->subclass == NC_FIELD);
		    if(!field->typ.basetype->touched) {keep=1;break;}
	        }	  
	        break;
	    default: break;				
	    }
	    if(keep) {
		listpush(sorted,(void*)sym);
		sym->touched = 1;
		added++;
	    }	    
	}
    } while(added > 0);
    /* Any untouched type => circular dependency*/
    for(i=0;i<listlength(typdefs);i++) {
	Symbol* tsym = (Symbol*)listget(typdefs,i);
	if(tsym->touched) continue;
	semerror(tsym->lineno,"Circular type dependency for type: %s",fullname(tsym));
    }
    listfree(typdefs);
    typdefs = sorted;
    /* fill in type typecodes*/
    for(i=0;i<listlength(typdefs);i++) {
        Symbol* sym = (Symbol*)listget(typdefs,i);
	if(sym->typ.basetype != NULL && sym->typ.typecode == NC_NAT)
	    sym->typ.typecode = sym->typ.basetype->typ.typecode;
    }
    /* Identify types containing vlens */
    for(i=0;i<listlength(typdefs);i++) {
        Symbol* tsym = (Symbol*)listget(typdefs,i);
	tagvlentypes(tsym);
    }
}
Esempio n. 3
0
/*
 * This function and pthread_create() do a lot of the same things.
 * It'd be nice to consolidate the common stuff in one place.
 */
static void
init_main_thread(struct pthread *thread)
{
	struct sched_param sched_param;

	/* Setup the thread attributes. */
	thr_self(&thread->tid);
	thread->attr = _pthread_attr_default;
	/*
	 * Set up the thread stack.
	 *
	 * Create a red zone below the main stack.  All other stacks
	 * are constrained to a maximum size by the parameters
	 * passed to mmap(), but this stack is only limited by
	 * resource limits, so this stack needs an explicitly mapped
	 * red zone to protect the thread stack that is just beyond.
	 */
	if (mmap(_usrstack - _thr_stack_initial -
	    _thr_guard_default, _thr_guard_default, 0, MAP_ANON,
	    -1, 0) == MAP_FAILED)
		PANIC("Cannot allocate red zone for initial thread");

	/*
	 * Mark the stack as an application supplied stack so that it
	 * isn't deallocated.
	 *
	 * XXX - I'm not sure it would hurt anything to deallocate
	 *       the main thread stack because deallocation doesn't
	 *       actually free() it; it just puts it in the free
	 *       stack queue for later reuse.
	 */
	thread->attr.stackaddr_attr = _usrstack - _thr_stack_initial;
	thread->attr.stacksize_attr = _thr_stack_initial;
	thread->attr.guardsize_attr = _thr_guard_default;
	thread->attr.flags |= THR_STACK_USER;

	/*
	 * Write a magic value to the thread structure
	 * to help identify valid ones:
	 */
	thread->magic = THR_MAGIC;

	thread->cancel_enable = 1;
	thread->cancel_async = 0;

	/* Initialize the mutex queue: */
	TAILQ_INIT(&thread->mutexq);
	TAILQ_INIT(&thread->pp_mutexq);

	thread->state = PS_RUNNING;

	_thr_getscheduler(thread->tid, &thread->attr.sched_policy,
		 &sched_param);
	thread->attr.prio = sched_param.sched_priority;

#ifdef _PTHREAD_FORCED_UNWIND
	thread->unwind_stackend = _usrstack;
#endif

	/* Others cleared to zero by thr_alloc() */
}
Esempio n. 4
0
void
_pthread_exit(void *status)
{
	struct pthread *curthread = _get_curthread();
	kse_critical_t crit;
	struct kse *curkse;

	/* Check if this thread is already in the process of exiting: */
	if ((curthread->flags & THR_FLAGS_EXITING) != 0) {
		char msg[128];
		snprintf(msg, sizeof(msg), "Thread %p has called "
		    "pthread_exit() from a destructor. POSIX 1003.1 "
		    "1996 s16.2.5.2 does not allow this!", curthread);
		PANIC(msg);
	}

	/*
	 * Flag this thread as exiting.  Threads should now be prevented
	 * from joining to this thread.
	 */
	THR_SCHED_LOCK(curthread, curthread);
	curthread->flags |= THR_FLAGS_EXITING;
	THR_SCHED_UNLOCK(curthread, curthread);
	
	/*
	 * To avoid signal-lost problem, if signals had already been
	 * delivered to us, handle it. we have already set EXITING flag
	 * so no new signals should be delivered to us.
	 * XXX this is not enough if signal was delivered just before
	 * thread called sigprocmask and masked it! in this case, we
	 * might have to re-post the signal by kill() if the signal
	 * is targeting process (not for a specified thread).
	 * Kernel has same signal-lost problem, a signal may be delivered
	 * to a thread which is on the way to call sigprocmask or thr_exit()!
	 */
	if (curthread->check_pending)
		_thr_sig_check_pending(curthread);
	/* Save the return value: */
	curthread->ret = status;
	while (curthread->cleanup != NULL) {
		_pthread_cleanup_pop(1);
	}
	if (curthread->attr.cleanup_attr != NULL) {
		curthread->attr.cleanup_attr(curthread->attr.arg_attr);
	}
	/* Check if there is thread specific data: */
	if (curthread->specific != NULL) {
		/* Run the thread-specific data destructors: */
		_thread_cleanupspecific();
	}
	if (!_kse_isthreaded())
		exit(0);
	crit = _kse_critical_enter();
	curkse = _get_curkse();
	KSE_LOCK_ACQUIRE(curkse, &_thread_list_lock);
	/* Use thread_list_lock */
	_thread_active_threads--;
	if ((_thread_scope_system <= 0 && _thread_active_threads == 1) ||
	    (_thread_scope_system > 0 && _thread_active_threads == 0)) {
		KSE_LOCK_RELEASE(curkse, &_thread_list_lock);
		_kse_critical_leave(crit);
		exit(0);
		/* Never reach! */
	}
	KSE_LOCK_RELEASE(curkse, &_thread_list_lock);

	/* This thread will never be re-scheduled. */
	KSE_LOCK(curkse);
	THR_SET_STATE(curthread, PS_DEAD);
	_thr_sched_switch_unlocked(curthread);
	/* Never reach! */

	/* This point should not be reached. */
	PANIC("Dead thread has resumed");
}
// The static Cast method is used to obtain a pointer to the derived class object
EXPORT_C TLinkKeyNotificationEvent& TLinkKeyNotificationEvent::Cast(const THCIEventBase& aEvent)
	{
	__ASSERT_DEBUG(aEvent.EventCode() == ELinkKeyNotificationEvent, PANIC(KSymbianCommandsEventsPanicCat, EWrongEventCode));
	return *(reinterpret_cast<TLinkKeyNotificationEvent*>(&const_cast<THCIEventBase&>(aEvent)));
	}
Esempio n. 6
0
void
_pthread_exit(void *status)
{
	struct pthread *curthread = _get_curthread();

	/* Check if this thread is already in the process of exiting: */
	if (curthread->cancelling) {
		char msg[128];
		snprintf(msg, sizeof(msg), "Thread %p has called "
		    "pthread_exit() from a destructor. POSIX 1003.1 "
		    "1996 s16.2.5.2 does not allow this!", curthread);
		PANIC(msg);
	}

	/* Flag this thread as exiting. */
	curthread->cancelling = 1;
	
	_thr_exit_cleanup();

	/* Save the return value: */
	curthread->ret = status;
	while (curthread->cleanup != NULL) {
		_pthread_cleanup_pop(1);
	}

	/* Check if there is thread specific data: */
	if (curthread->specific != NULL) {
		/* Run the thread-specific data destructors: */
		_thread_cleanupspecific();
	}

	if (!_thr_isthreaded())
		exit(0);

	THREAD_LIST_LOCK(curthread);
	_thread_active_threads--;
	if (_thread_active_threads == 0) {
		THREAD_LIST_UNLOCK(curthread);
		exit(0);
		/* Never reach! */
	}
	THREAD_LIST_UNLOCK(curthread);

	/* Tell malloc that the thread is exiting. */
	_malloc_thread_cleanup();

	THREAD_LIST_LOCK(curthread);
	THR_LOCK(curthread);
	curthread->state = PS_DEAD;
	if (curthread->flags & THR_FLAGS_NEED_SUSPEND) {
		curthread->cycle++;
		_thr_umtx_wake(&curthread->cycle, INT_MAX, 0);
	}
	THR_UNLOCK(curthread);
	/*
	 * Thread was created with initial refcount 1, we drop the
	 * reference count to allow it to be garbage collected.
	 */
	curthread->refcount--;
	if (curthread->tlflags & TLFLAGS_DETACHED)
		THR_GCLIST_ADD(curthread);
	THREAD_LIST_UNLOCK(curthread);
	if (!curthread->force_exit && SHOULD_REPORT_EVENT(curthread, TD_DEATH))
		_thr_report_death(curthread);

	/*
	 * Kernel will do wakeup at the address, so joiner thread
	 * will be resumed if it is sleeping at the address.
	 */
	thr_exit(&curthread->tid);
#ifndef __AVM2__ // might exit if we're impersonating another thread!
	PANIC("thr_exit() returned");
#endif
	/* Never reach! */
}
Esempio n. 7
0
void spawner_new_c::setup_stream_(const std::string& stream_str, pipes_t this_pipe_type, runner* this_runner) {
    size_t pos = stream_str.find(".");
    // malformed argument
    PANIC_IF(pos == std::string::npos);
    size_t index = stoi(stream_str.substr(1, pos - 1), nullptr, 10);
    std::string stream = stream_str.substr(pos + 1);
    // invalid index
    PANIC_IF(index >= runners.size() || index < 0);
    pipes_t other_pipe_type;
    if (stream == "stderr") {
        other_pipe_type = STD_ERROR_PIPE;
    }
    else if (stream == "stdin") {
        other_pipe_type = STD_INPUT_PIPE;
    }
    else if (stream == "stdout") {
        other_pipe_type = STD_OUTPUT_PIPE;
    }
    else {
        PANIC("invalid stream name");
    }
    runner *target_runner = runners[index];
    std::shared_ptr<input_pipe_c> input_pipe = nullptr;
    std::shared_ptr<output_pipe_c> output_pipe = nullptr;
    pipes_t out_pipe_type = STD_ERROR_PIPE;
    runner* out_pipe_runner = nullptr;
    runner* in_pipe_runner = nullptr;

    if (this_pipe_type == STD_INPUT_PIPE && other_pipe_type != STD_INPUT_PIPE) {

        input_pipe = std::static_pointer_cast<input_pipe_c>(this_runner->get_pipe(this_pipe_type));
        output_pipe = std::static_pointer_cast<output_pipe_c>(target_runner->get_pipe(other_pipe_type));
        out_pipe_type = other_pipe_type;
        out_pipe_runner = target_runner;
        in_pipe_runner = this_runner;

    } else if (this_pipe_type != STD_INPUT_PIPE && other_pipe_type == STD_INPUT_PIPE) {

        input_pipe = std::static_pointer_cast<input_pipe_c>(target_runner->get_pipe(other_pipe_type));
        output_pipe = std::static_pointer_cast<output_pipe_c>(this_runner->get_pipe(this_pipe_type));
        out_pipe_type = this_pipe_type;
        out_pipe_runner = this_runner;
        in_pipe_runner = target_runner;
    } else {
        PANIC("invalid pipe mapping");
    }

    std::shared_ptr<duplex_buffer_c> buffer = std::make_shared<duplex_buffer_c>();
    in_pipe_runner->duplex_buffers.push_back(buffer);
    out_pipe_runner->duplex_buffers.push_back(buffer);
    input_pipe->add_input_buffer(buffer);
    output_pipe->add_output_buffer(buffer);

    int out_runner_index = -1;
    int in_runner_index = -1;
    for (size_t i = 0; i < runners.size(); i++) {
        if (runners[i] == out_pipe_runner) {
            out_runner_index = i;
        }
        if (runners[i] == in_pipe_runner) {
            in_runner_index = i;
        }
    }

    if (out_runner_index == controller_index_) {
        int index = in_runner_index;
        if (index > controller_index_) {
            index--;
        }
        buffer_to_runner_index_[buffer] = index + 1;
    }

    if (control_mode_enabled
            && out_pipe_type == STD_OUTPUT_PIPE
            && !output_pipe->process_message) {

        if (out_pipe_runner->get_options().controller) {
            output_pipe->process_message = [=](const std::string& message, output_pipe_c* pipe) {
                process_controller_message_(message, pipe);
            };
        } else {
            int index = out_runner_index;
            if (index > controller_index_) {
                index--;
            }
            output_pipe->process_message = [=](const std::string& message, output_pipe_c* pipe) {
                process_normal_message_(message, pipe, index + 1);
            };
        }
    }
}
Esempio n. 8
0
/*!
  \class Worker
  Run worker.
  \public
  @param[in] server_name Server IP address (ex: 127.0.0.1).
  @param[in] port The port number (ex: 80).
*/
void Worker::run(char* server_name, char* port)
{
  // Create new socket class instance.
  Socket *socket = new Socket();
  
  // Connect to the server.
  socket->connect_(server_name, port);
  
  std::string hello = WORKER_HELLO;
  
  // "Introduce yourself to the server".
  socket->send_(hello);

  std::string data_result = "";
  std::string data_errors = "";
  std::string data_inf = "";
  std::string data_to_send = "";
  std::string data_filename = "";
  
  std::string data_recive = "";

  std::string compile_result = "";
  char ch;
  int pos1, pos2;

  while(true)
  {
    data_result = "";
    data_recive = "";
    data_errors = "";
    data_filename = "";
    data_inf = "";
    pos1 = 0;
    pos2 = 0;

    if (!SELF_DEBUG)
    {
	std::cout << "Czekam na dane...\n";

        try
        {
          data_recive = socket->recive_();
        }
        catch(char *str)
        {
           PANIC(-1, str);
        }
        catch(...)
        {
           PANIC(-1, "Exception..");
        }
    }
    else
    {
         data_recive = DEBUG_SOURCE;
    }

    pos1 = data_recive.find(DATA_SEPARATOR);
    pos2 = data_recive.find(DATA_SEPARATOR, pos1+1,16);
    data_filename = data_recive.substr(0, pos1);
    data_recive = data_recive.substr(pos1+16, pos2-25);
    
    // Write data from client to the file.
    File::write(INPUT_FILE, data_recive);

    /*
    FILE* fp = fopen(INPUT_FILE, "w");
    fprintf(fp,"%s",data_recive.c_str() );
    fclose(fp);
    */

    // Get g++ compiler version.
    std::cout << "Zbieram dane o kompilatorze...\n";
    system("g++ -v 2>inf.sr");
    
    //std::string result;
    //char tmp[1024];
    //FILE *term = popen("g++4 -c -o output.o output.cpp", "r");
    
    //while((fgets(tmp, 1024, term)) != 0)
    //{
    //     result += std::string(tmp);
    //     tmp[0] = '\0';
    //}

    // Compling...
    std::cout << "Kompiluje dane...\n";
    system("./bash_create_output");
    //system("python ./x.rb");
    system("g++ -c -o output.o output.cpp 2> errors.sr");
    //execl("/bin/sh","./bash_compile","bash_compile", NULL);
    
    // Get results from files using File namespace.
    std::cout << "Odczytuje dane...\n";

    data_result = File::read_bin(OUTPUT_FILE);
    data_errors = File::read(ERRORS_FILE);
    data_inf = File::read(INF_FILE);

       
    /*
    fp = fopen(OUTPUT_FILE, "r");
    do 
    {
      ch = fgetc(fp);
      data_result += ch ;
    }while(ch != EOF);
    fclose(fp);

    fp = fopen(ERRORS_FILE, "r");
    do 
    {
      ch = fgetc(fp);
      data_errors += ch ;
    }while(ch != EOF);
    fclose(fp);

    fp = fopen(INF_FILE, "r");
    do 
    {
      ch = fgetc(fp);
      data_inf += ch ;
    }while(ch != EOF);
    fclose(fp); */

    // Collect datas.
    data_to_send = data_filename;
    data_to_send += DATA_SEPARATOR;
    data_to_send += data_inf;
    data_to_send += DATA_SEPARATOR;
    data_to_send += data_errors;
    data_to_send += DATA_SEPARATOR;
    data_to_send += data_result;
    data_to_send += DATA_SEPARATOR;

    //std::cout << "\n\n\n\n" << data_result << "\n\n\n\n";

    if (!SELF_DEBUG)
    {
	std::cout << "Wysylam dane...\n";
        socket->send_(data_to_send);
	std::cout << "Dane wysłano.\n\n";
    }

    // Remove tmp files.
    system("rm -f ./output.cpp ./output.o ./errors.sr ./inf.sr");

    if (SELF_DEBUG)
    {
       //std::cout << data_to_send;
       std::cout << data_recive;
       break;
    }
  }
}
Esempio n. 9
0
File: page.c Progetto: yemxx/shayang
void page_fault(struct TrapFrame * tf)
{
	PANIC("Page fault!");
}
Esempio n. 10
0
void CSdlAppServ::RunL()
    {
    if(iStatus == KErrNone)
        {
        switch(iService)
            {
            case CSdlAppServ::EAppSrvWaitDsa:
            	//EpocSdlEnv::SetWaitDsa();
            	iReturnValue = EpocSdlEnv::IsDsaAvailable();
            	break;
           	/* case CSdlAppServ::EAppSrvStopThread:
           	 	if(gEpocEnv->iDsa != NULL)
            		gEpocEnv->iDsa->SetSuspend();
            	break;*/
            case EpocSdlEnv::EDisableKeyBlocking:
                EnvUtils::DisableKeyBlocking();
                break;
         
            case EpocSdlEnv::ESetAppOrientation:
                iReturnValue = EnvUtils::SetAppOrientation(static_cast<CSDL::TAppOrientation>(iReturnValue));
                break;    
                
           
            case EAppSrvWindowPointerCursorMode:
                iReturnValue = gEpocEnv->iDsa != NULL ?
                 gEpocEnv->iDsa->Session().PointerCursorMode() : KErrNotReady; 
                break;
                
            case EAppSrvDsaStatus:
            	if(gEpocEnv->iDsa != NULL)
            		gEpocEnv->iDsa->Stop();
                iReturnValue = KErrNone;
                break;
            case CDsa::ERequestUpdate:
            	gEpocEnv->iDsa->UnlockHWSurfaceRequestComplete();
            	break;
            case EVideoUpdate:
                VideoUpdate();
                break;
            case EAppSrvNoop:
                break;
            case MSDLObserver::EEventResume:
            case MSDLObserver::EEventSuspend:
            case MSDLObserver::EEventScreenSizeChanged:
            case MSDLObserver::EEventWindowReserved:
            case MSDLObserver::EEventKeyMapInit:
            case MSDLObserver::EEventWindowNotAvailable:
            case MSDLObserver::EEventMainExit:
            case MSDLObserver::EEventVolumeChange:
            case MSDLObserver::EEventScreenSurfaceCreated:
            	iReturnValue = ObserverEvent(iService, iReturnValue);
            	HandleObserverValue(iService, iReturnValue, ETrue);
            	break;
            default:
                PANIC(KErrNotSupported);
            }
       /*
        iStatus = KRequestPending;
        iStatusPtr = &iStatus;
        SetActive();
        */
        }
    if(EnvUtils::IsOwnThreaded())
    	iSema.Signal();
    }
Esempio n. 11
0
/***************************************************************************
 *      draw_clock()
 * Draws a five-digit (-x:yy) clock in the center of the screen.
 *********************************************************************PROTO*/
void
draw_clock(int seconds)
{
    static int old_seconds = -111;	/* last time we drew */
    static SDL_Surface * digit[12];
    char buf[16];
    static int w = -1, h= -1; /* max digit width/height */
    int i, c;

    if (seconds == old_seconds || gametype == DEMO) return;

    if (old_seconds == -111) {
	/* setup code */

	for (i=0;i<10;i++) {
	    SPRINTF(buf,"%d",i);
	    digit[i] = TTF_RenderText_Blended(font,buf,color_blue);
	}
	SPRINTF(buf,":"); digit[10] = TTF_RenderText_Blended(font,buf,color_red);
	SPRINTF(buf,"-"); digit[11] = TTF_RenderText_Blended(font,buf,color_red);

	for (i=0;i<12;i++) {
	    Assert(digit[i]);
	    /* the colorkey and display format are already done */
	    /* find the largest dimensions */
	    if (digit[i]->w > w) w = digit[i]->w;
	    if (digit[i]->h > h) h = digit[i]->h;
	}
    }

    old_seconds = seconds;

    SPRINTF(buf,"%d:%02d",seconds / 60, seconds % 60);

    c = layout.time.x;
    layout.time.w = w * 5;
    layout.time.h = h;

    SDL_FillRect(widget_layer, &layout.time, int_solid_black); 

    if (strlen(buf) > 5)
	SPRINTF(buf,"----");

    if (strlen(buf) < 5)
	layout.time.x += ((5 - strlen(buf)) * w) / 2;


    for (i=0;buf[i];i++) {
	SDL_Surface * to_blit;

	if (buf[i] >= '0' && buf[i] <= '9')
	    to_blit = digit[buf[i] - '0'];
	else if (buf[i] == ':')
	    to_blit = digit[10];
	else if (buf[i] == '-')
	    to_blit = digit[11];
	else PANIC("unknown character in clock string [%s]",buf);

	/* center the letter horizontally */
	if (w > to_blit->w) layout.time.x += (w - to_blit->w) / 2;
	layout.time.w = to_blit->w;
	layout.time.h = to_blit->h;
	/*
	Debug("[%d+%d, %d+%d]\n",
		clockPos.x,clockPos.w,clockPos.y,clockPos.h);
		*/
	SDL_BlitSafe(to_blit, NULL, widget_layer, &layout.time);
	if (w > to_blit->w) layout.time.x -= (w - to_blit->w) / 2;
	layout.time.x += w;
    }

    layout.time.x = c;
    /*    clockPos.x = (screen->w - (w * 5)) / 2;*/
    layout.time.w = w * 5;
    layout.time.h = h;
    SDL_BlitSafe(flame_layer, &layout.time, screen, &layout.time);
    SDL_BlitSafe(widget_layer, &layout.time, screen, &layout.time);
    SDL_UpdateSafe(screen, 1, &layout.time);

    return;
}
Esempio n. 12
0
ssize_t mq_doreceive(mqd_t mqdes, mqmsg_t *mqmsg, void *ubuffer, int *prio)
{
  FAR _TCB   *btcb;
  irqstate_t  saved_state;
  FAR msgq_t *msgq;
  ssize_t     rcvmsglen;

  /* Get the length of the message (also the return value) */

  rcvmsglen = mqmsg->msglen;

  /* Copy the message into the caller's buffer */

  memcpy(ubuffer, (const void*)mqmsg->mail, rcvmsglen);

  /* Copy the message priority as well (if a buffer is provided) */

  if (prio)
    {
      *prio = mqmsg->priority;
    }

  /* We are done with the message.  Deallocate it now. */

  mq_msgfree(mqmsg);

  /* Check if any tasks are waiting for the MQ not full event. */

  msgq = mqdes->msgq;
  if (msgq->nwaitnotfull > 0)
    {
      /* Find the highest priority task that is waiting for
       * this queue to be not-full in g_waitingformqnotfull list.
       * This must be performed in a critical section because
       * messages can be sent from interrupt handlers.
       */

      saved_state = irqsave();
      for (btcb = (FAR _TCB*)g_waitingformqnotfull.head;
           btcb && btcb->msgwaitq != msgq;
           btcb = btcb->flink);

      /* If one was found, unblock it.  NOTE:  There is a race
       * condition here:  the queue might be full again by the
       * time the task is unblocked
       */

      if (!btcb)
        {
          PANIC(OSERR_MQNOTFULLCOUNT);
        }
      else
        {
          btcb->msgwaitq = NULL;
          msgq->nwaitnotfull--;
          up_unblock_task(btcb);
        }
      irqrestore(saved_state);
    }

  /* Return the length of the message transferred to the user buffer */

  return rcvmsglen;
}
Esempio n. 13
0
static int
cond_wait_user(struct pthread_cond *cvp, struct pthread_mutex *mp,
               const struct timespec *abstime, int cancel)
{
    struct pthread	*curthread = _get_curthread();
    struct sleepqueue *sq;
    int	recurse;
    int	error;
    int	defered;

    if (curthread->wchan != NULL)
        PANIC("thread was already on queue.");

    if (cancel)
        _thr_testcancel(curthread);

    _sleepq_lock(cvp);
    /*
     * set __has_user_waiters before unlocking mutex, this allows
     * us to check it without locking in pthread_cond_signal().
     */
    cvp->__has_user_waiters = 1;
    defered = 0;
    (void)_mutex_cv_unlock(mp, &recurse, &defered);
    curthread->mutex_obj = mp;
    _sleepq_add(cvp, curthread);
    for(;;) {
        _thr_clear_wake(curthread);
        _sleepq_unlock(cvp);
        if (defered) {
            defered = 0;
            if ((mp->m_lock.m_owner & UMUTEX_CONTESTED) == 0)
                (void)_umtx_op_err(&mp->m_lock, UMTX_OP_MUTEX_WAKE2,
                                   mp->m_lock.m_flags, 0, 0);
        }
        if (curthread->nwaiter_defer > 0) {
            _thr_wake_all(curthread->defer_waiters,
                          curthread->nwaiter_defer);
            curthread->nwaiter_defer = 0;
        }

        if (cancel) {
            _thr_cancel_enter2(curthread, 0);
            error = _thr_sleep(curthread, cvp->__clock_id, abstime);
            _thr_cancel_leave(curthread, 0);
        } else {
            error = _thr_sleep(curthread, cvp->__clock_id, abstime);
        }

        _sleepq_lock(cvp);
        if (curthread->wchan == NULL) {
            error = 0;
            break;
        } else if (cancel && SHOULD_CANCEL(curthread)) {
            sq = _sleepq_lookup(cvp);
            cvp->__has_user_waiters =
                _sleepq_remove(sq, curthread);
            _sleepq_unlock(cvp);
            curthread->mutex_obj = NULL;
            _mutex_cv_lock(mp, recurse);
            if (!THR_IN_CRITICAL(curthread))
                _pthread_exit(PTHREAD_CANCELED);
            else /* this should not happen */
                return (0);
        } else if (error == ETIMEDOUT) {
            sq = _sleepq_lookup(cvp);
            cvp->__has_user_waiters =
                _sleepq_remove(sq, curthread);
            break;
        }
    }
    _sleepq_unlock(cvp);
    curthread->mutex_obj = NULL;
    _mutex_cv_lock(mp, recurse);
    return (error);
}
/*
 * Asynchronous I/O callback launched when framebuffer notifications are ready
 * to be read.
 * Param:
 *  opaque - ClientFramebuffer instance.
 */
static void
_clientfb_read_cb(void* opaque)
{
    ClientFramebuffer* fb_client = opaque;
    int  ret;

    // Read updates while they are immediately available.
    for (;;) {
        // Read next chunk of data.
        ret = read(fb_client->sock, fb_client->reader_buffer + fb_client->reader_offset,
                   fb_client->reader_bytes - fb_client->reader_offset);
        if (ret == 0) {
            /* disconnection ! */
            clientfb_destroy(fb_client);
            return;
        }
        if (ret < 0) {
            if (errno == EINTR) {
                /* loop on EINTR */
                continue;
            } else if (errno == EWOULDBLOCK || errno == EAGAIN) {
                // Chunk is not avalable at this point. Come back later.
                return;
            }
        }

        fb_client->reader_offset += ret;
        if (fb_client->reader_offset != fb_client->reader_bytes) {
            // There are still some data left in the pipe.
            continue;
        }

        // All expected data has been read. Time to change the state.
        if (fb_client->fb_state == WAIT_HEADER) {
            // Update header has been read. Prepare for the pixels.
            fb_client->fb_state = WAIT_PIXELS;
            fb_client->reader_offset = 0;
            fb_client->reader_bytes = fb_client->update_header.w *
                                      fb_client->update_header.h *
                                      (fb_client->bits_per_pixel / 8);
            fb_client->reader_buffer = malloc(fb_client->reader_bytes);
            if (fb_client->reader_buffer == NULL) {
                PANIC("Unable to allocate memory for framebuffer update\n");
            }
        } else {
            // Pixels have been read. Prepare for the header.
             uint8_t* pixels = fb_client->reader_buffer;

            fb_client->fb_state = WAIT_HEADER;
            fb_client->reader_offset = 0;
            fb_client->reader_bytes = sizeof(FBUpdateMessage);
            fb_client->reader_buffer = (uint8_t*)&fb_client->update_header;

            // Perform the update. Note that pixels buffer must be freed there.
            update_rect(fb_client->fb, fb_client->update_header.x,
                        fb_client->update_header.y, fb_client->update_header.w,
                        fb_client->update_header.h, fb_client->bits_per_pixel,
                        pixels);
        }
    }
}
Esempio n. 15
0
void cluster_counter (int  no_of_things,  int *neighbors[], int * mask,
		     int cluster_count_per_size[], int * no_of_clusters,
		      int * max_size, int * secnd_max_size , int * clusters[]){
	

    /* arrays */ 
    static int*  * flag_ptr;          /* array of pointers to cluster flags*/
    static int   * flags;             /* array of available flags */
    static int   * bin  ;             /* for counting different clusters */
    /* counters, booleans etc */
    int flag_ctr, this_thing, other_thing; 
    int new_flag, cluster_count, isolated_count;
    int this_value, other_value, max_cluster, second_max;
    int color;
    
    /* for allocation purposes */
    static int first = 1;

    if ( first ) { /* do allocation */
	first = 0;
	/* flag ptrs   */
	flag_ptr     = calloc (no_of_things, sizeof(int*));
	/* flags        */
	flags        = calloc (no_of_things, sizeof(int));
	/* bins         */
	bin          = calloc (no_of_things, sizeof(int));
    }
    /* check if all alive: */ 
    if ( !( flag_ptr && flags && bin) ) {
	PANIC ("Error allocating memory in ClusterCounter."); 
    }

	
    /* set all the flags to 0 */
    memset (flags, 0, no_of_things*sizeof(int));
    /* the number of times new flag is assigned:*/
    new_flag = 0;
    /* set all the flag ptrs  to NULL */
    memset (flag_ptr, 0, no_of_things*sizeof(int*));
    /* color by cluster */ 
     
    for (this_thing=0; this_thing < no_of_things; this_thing++) {
	if (  mask [this_thing] ) {
	    for (other_thing=this_thing+1; other_thing < no_of_things; other_thing++) {
		if (  mask [other_thing] && neighbors[this_thing][other_thing]) {
		    if (flag_ptr[this_thing]){
			if (flag_ptr[other_thing]){ /*if both ptrs assigned*/
				/*************************************************/
				/* look at the flag values they are assigned to: */
			    if ( *flag_ptr[this_thing]  !=  *flag_ptr[other_thing] ) { 
				/* i.e. do something only if they differ*/
				this_value   = *flag_ptr[this_thing];
				other_value  = *flag_ptr[other_thing];
				for ( flag_ctr=0; flag_ctr < new_flag; flag_ctr++ ) {
				    if ( flags[flag_ctr] == other_value) {
					flags[flag_ctr] = this_value;
				    }
				}
				    
			    }
			} else {                       /* one not assigned*/ 
				/*************************************************/
			    flag_ptr[other_thing] = flag_ptr[this_thing];
			}
		    } else {
			if (flag_ptr[other_thing]){ /* one not assigned*/
				/*************************************************/
			    flag_ptr[this_thing]  = flag_ptr[other_thing];
			} else {                      /* both null*/
				/*************************************************/
			    /*  create new flag*/
			    flags[new_flag] = new_flag;
				/*  make both ptrs point there*/
			    flag_ptr[this_thing]  = flag_ptr[other_thing] = &flags[new_flag];
			    new_flag++;
			}
		    
		    }

		}
	    }
	}
    }

    /*count the clusters*/
    memset (bin, 0, no_of_things*sizeof(int));
    memset (clusters[0], 0, (no_of_things+1)*(no_of_things+1)*sizeof(int));
    cluster_count = 0;
    isolated_count = 0;
    for (this_thing=0; this_thing < no_of_things; this_thing++) {
	if (  mask [this_thing] ) {
	    if ( !flag_ptr[this_thing] ) {
		isolated_count++;
		clusters [0][0]++;
		clusters [0][ clusters [0][0] ] = this_thing;
	    } else {
		color = *flag_ptr[this_thing];
		if ( ! bin[color] ){
		    cluster_count ++;
		}
		bin[color] ++;
		color += 1;
		clusters [color][0]++;
		clusters [color][ clusters [color][0] ] = this_thing;
	    }
	}
     }



    /* find max cluster */
    if (isolated_count == 0 ) {
	second_max = max_cluster = 0;
    } else {
	second_max = max_cluster = 1;
    }
    memset ( cluster_count_per_size, 0, no_of_things * sizeof(int));
	    
    for ( flag_ctr=0; flag_ctr < new_flag; flag_ctr++ ) {
	cluster_count_per_size[ bin[flag_ctr] ] ++;
	if ( bin[flag_ctr] >= max_cluster ) {
	    second_max = max_cluster;
	    max_cluster = bin[flag_ctr];
	}
    }
    cluster_count_per_size[1] = isolated_count;
    
    /* save the count and the max cluster */
    * no_of_clusters = cluster_count+isolated_count;
    * max_size = max_cluster;
    * secnd_max_size = second_max;
    return;
}
Esempio n. 16
0
void up_reprioritize_rtr(struct tcb_s *tcb, uint8_t priority)
{
  /* Verify that the caller is sane */

  if (tcb->task_state < FIRST_READY_TO_RUN_STATE ||
      tcb->task_state > LAST_READY_TO_RUN_STATE
#if SCHED_PRIORITY_MIN > 0
      || priority < SCHED_PRIORITY_MIN
#endif
#if SCHED_PRIORITY_MAX < UINT8_MAX
      || priority > SCHED_PRIORITY_MAX
#endif
    )
    {
       PANIC();
    }
  else
    {
      struct tcb_s *rtcb = this_task();
      bool switch_needed;

      sinfo("TCB=%p PRI=%d\n", tcb, priority);

      /* Remove the tcb task from the ready-to-run list.
       * sched_removereadytorun will return true if we just
       * remove the head of the ready to run list.
       */

      switch_needed = sched_removereadytorun(tcb);

      /* Setup up the new task priority */

      tcb->sched_priority = (uint8_t)priority;

      /* Return the task to the specified blocked task list.
       * sched_addreadytorun will return true if the task was
       * added to the new list.  We will need to perform a context
       * switch only if the EXCLUSIVE or of the two calls is non-zero
       * (i.e., one and only one the calls changes the head of the
       * ready-to-run list).
       */

      switch_needed ^= sched_addreadytorun(tcb);

      /* Now, perform the context switch if one is needed */

      if (switch_needed)
        {
          /* If we are going to do a context switch, then now is the right
           * time to add any pending tasks back into the ready-to-run list.
           * task list now
           */

          if (g_pendingtasks.head)
            {
              sched_mergepending();
            }

          /* Update scheduler parameters */

          sched_suspend_scheduler(rtcb);

         /* Are we in an interrupt handler? */

          if (g_current_regs)
            {
              /* Yes, then we have to do things differently.
               * Just copy the g_current_regs into the OLD rtcb.
               */

               up_savestate(rtcb->xcp.regs);

              /* Restore the exception context of the rtcb at the (new) head
               * of the ready-to-run task list.
               */

              rtcb = this_task();

              /* Update scheduler parameters */

              sched_resume_scheduler(rtcb);

              /* Then switch contexts.  Any necessary address environment
               * changes will be made when the interrupt returns.
               */

              up_restorestate(rtcb->xcp.regs);
            }

          /* No, then we will need to perform the user context switch */

          else
            {
              /* Switch context to the context of the task at the head of the
               * ready to run list.
               */

              struct tcb_s *nexttcb = this_task();

#ifdef CONFIG_ARCH_ADDRENV
              /* Make sure that the address environment for the previously
               * running task is closed down gracefully (data caches dump,
               * MMU flushed) and set up the address environment for the new
               * thread at the head of the ready-to-run list.
               */

              (void)group_addrenv(nexttcb);
#endif
              /* Update scheduler parameters */

              sched_resume_scheduler(nexttcb);

              /* Then switch contexts */

              up_switchcontext(rtcb->xcp.regs, nexttcb->xcp.regs);

              /* up_switchcontext forces a context switch to the task at the
               * head of the ready-to-run list.  It does not 'return' in the
               * normal sense.  When it does return, it is because the blocked
               * task is again ready to run and has execution priority.
               */
            }
        }
    }
}
Esempio n. 17
0
void
_thr_assert_lock_level()
{
	PANIC("locklevel <= 0");
}
Esempio n. 18
0
VOID
LpxAllocateConnection(
    IN PDEVICE_CONTEXT DeviceContext,
    OUT PTP_CONNECTION *TransportConnection
    )

/*++

Routine Description:

    This routine allocates storage for a transport connection. Some
    minimal initialization is done.

    NOTE: This routine is called with the device context spinlock
    held, or at such a time as synchronization is unnecessary.

Arguments:

    DeviceContext - the device context for this connection to be
        associated with.

    TransportConnection - Pointer to a place where this routine will
        return a pointer to a transport connection structure. Returns
        NULL if the storage cannot be allocated.

Return Value:

    None.

--*/

{

    PTP_CONNECTION Connection;

    if ((DeviceContext->MemoryLimit != 0) &&
            ((DeviceContext->MemoryUsage + sizeof(TP_CONNECTION)) >
                DeviceContext->MemoryLimit)) {
        PANIC("LPX: Could not allocate connection: limit\n");
        LpxWriteResourceErrorLog(
            DeviceContext,
            EVENT_TRANSPORT_RESOURCE_LIMIT,
            103,
            sizeof(TP_CONNECTION),
            CONNECTION_RESOURCE_ID);
        *TransportConnection = NULL;
        return;
    }

    Connection = (PTP_CONNECTION)ExAllocatePoolWithTag (
                                     NonPagedPool,
                                     sizeof (TP_CONNECTION),
                                     LPX_MEM_TAG_TP_CONNECTION);
    if (Connection == NULL) {
        PANIC("LPX: Could not allocate connection: no pool\n");
        LpxWriteResourceErrorLog(
            DeviceContext,
            EVENT_TRANSPORT_RESOURCE_POOL,
            203,
            sizeof(TP_CONNECTION),
            CONNECTION_RESOURCE_ID);
        *TransportConnection = NULL;
        return;
    }
    RtlZeroMemory (Connection, sizeof(TP_CONNECTION));

    IF_LPXDBG (LPX_DEBUG_DYNAMIC) {
        LpxPrint1 ("ExAllocatePool Connection %p\n", Connection);
    }

    DeviceContext->MemoryUsage += sizeof(TP_CONNECTION);
    ++DeviceContext->ConnectionAllocated;

    Connection->Type = LPX_CONNECTION_SIGNATURE;
    Connection->Size = sizeof (TP_CONNECTION);

    Connection->Provider = DeviceContext;
    Connection->ProviderInterlock = &DeviceContext->Interlock;
    KeInitializeSpinLock (&Connection->SpinLock);

    InitializeListHead (&Connection->LinkList);
    InitializeListHead (&Connection->AddressFileList);
    InitializeListHead (&Connection->AddressList);

    *TransportConnection = Connection;

}   /* LpxAllocateConnection */
Esempio n. 19
0
void up_syscall(uint32_t *regs)
{
  lldbg("Syscall from 0x%x\n", regs[REG_PC]);
  current_regs = regs;
  PANIC();
}
Esempio n. 20
0
void up_block_task(_TCB *tcb, tstate_t task_state)
{
  /* Verify that the context switch can be performed */

  if ((tcb->task_state < FIRST_READY_TO_RUN_STATE) ||
      (tcb->task_state > LAST_READY_TO_RUN_STATE))
    {
      PANIC(OSERR_BADBLOCKSTATE);
    }
  else
    {
      _TCB *rtcb = (_TCB*)g_readytorun.head;
      bool switch_needed;

      /* Remove the tcb task from the ready-to-run list.  If we
       * are blocking the task at the head of the task list (the
       * most likely case), then a context switch to the next
       * ready-to-run task is needed. In this case, it should
       * also be true that rtcb == tcb.
       */

      switch_needed = sched_removereadytorun(tcb);

      /* Add the task to the specified blocked task list */

      sched_addblocked(tcb, (tstate_t)task_state);

      /* If there are any pending tasks, then add them to the g_readytorun
       * task list now
       */

      if (g_pendingtasks.head)
        {
          switch_needed |= sched_mergepending();
        }

      /* Now, perform the context switch if one is needed */

      if (switch_needed)
        {
          /* Are we in an interrupt handler? */

          if (current_regs)
            {
              /* Yes, then we have to do things differently.
               * Just copy the current_regs into the OLD rtcb.
               */

               up_savestate(rtcb->xcp.regs);

              /* Restore the exception context of the rtcb at the (new) head 
               * of the g_readytorun task list.
               */

              rtcb = (_TCB*)g_readytorun.head;

              /* Then switch contexts */

              up_restorestate(rtcb->xcp.regs);
            }

          /* Copy the user C context into the TCB at the (old) head of the
           * g_readytorun Task list. if up_saveusercontext returns a non-zero
           * value, then this is really the previously running task restarting!
           */

          else if (!up_saveusercontext(rtcb->xcp.regs))
            {
              /* Restore the exception context of the rtcb at the (new) head 
               * of the g_readytorun task list.
               */

              rtcb = (_TCB*)g_readytorun.head;

              /* Then switch contexts */

              up_fullcontextrestore(rtcb->xcp.regs);
            }
        }
    }
}
Esempio n. 21
0
uint32_t *up_doirq(int irq, uint32_t* regs)
{
  up_ledon(LED_INIRQ);
#ifdef CONFIG_SUPPRESS_INTERRUPTS
  PANIC();
#else
  if ((unsigned)irq < NR_IRQS)
    {
       uint32_t *savestate;

       /* Nested interrupts are not supported in this implementation.  If
        * you want to implement nested interrupts, you would have to (1)
        * change the way that current_regs is handled and (2) the design
        * associated with CONFIG_ARCH_INTERRUPTSTACK.  The savestate
        * variable will not work for that purpose as implemented here
        * because only the outermost nested interrupt can result in a
        * context switch (it can probably be deleted).
        */

       /* Current regs non-zero indicates that we are processing
        * an interrupt; current_regs is also used to manage
        * interrupt level context switches.
        */

       savestate    = (uint32_t*)current_regs;
       current_regs = regs;

       /* Mask and acknowledge the interrupt (if supported by the chip) */

#ifndef CONFIG_ARCH_NOINTC
       up_maskack_irq(irq);
#endif

       /* Deliver the IRQ */

       irq_dispatch(irq, regs);

       /* Get the current value of regs... it may have changed because
        * of a context switch performed during interrupt processing.
        */

       regs = current_regs;

       /* Restore the previous value of current_regs.  NULL would indicate that
        * we are no longer in an interrupt handler.  It will be non-NULL if we
        * are returning from a nested interrupt.
        */

       current_regs = savestate;

       /* Unmask the last interrupt (global interrupts are still
        * disabled.
        */

#ifndef CONFIG_ARCH_NOINTC
       up_enable_irq(irq);
#endif
    }
  up_ledoff(LED_INIRQ);
#endif
  return regs;
}
Esempio n. 22
0
int up_hardfault(int irq, FAR void *context)
{
#if defined(CONFIG_DEBUG_HARDFAULT) || !defined(CONFIG_ARMV7M_USEBASEPRI)
  uint32_t *regs = (uint32_t*)context;
#endif

  /* Get the value of the program counter where the fault occurred */

#ifndef CONFIG_ARMV7M_USEBASEPRI
  uint16_t *pc = (uint16_t*)regs[REG_PC] - 1;

  /* Check if the pc lies in known FLASH memory.
   * REVISIT:  What if the PC lies in "unknown" external memory?  Best
   * use the BASEPRI register if you have external memory.
   */

#ifdef CONFIG_BUILD_PROTECTED
  /* In the kernel build, SVCalls are expected in either the base, kernel
   * FLASH region or in the user FLASH region.
   */

  if (((uintptr_t)pc >= (uintptr_t)&_stext &&
       (uintptr_t)pc <  (uintptr_t)&_etext) ||
      ((uintptr_t)pc >= (uintptr_t)USERSPACE->us_textstart &&
       (uintptr_t)pc <  (uintptr_t)USERSPACE->us_textend))
#else
  /* SVCalls are expected only from the base, kernel FLASH region */

  if ((uintptr_t)pc >= (uintptr_t)&_stext &&
      (uintptr_t)pc <  (uintptr_t)&_etext)
#endif
    {
      /* Fetch the instruction that caused the Hard fault */

      uint16_t insn = *pc;

      /* If this was the instruction 'svc 0', then forward processing
       * to the SVCall handler
       */

      if (insn == INSN_SVC0)
        {
          return up_svcall(irq, context);
        } else {
          hfdbg("  PC: %p INSN: %04x\n", pc, insn);
        }
    }
#endif

  /* Dump some hard fault info */

  hfdbg("Hard Fault:\n");
  hfdbg("  IRQ: %d regs: %p\n", irq, regs);
  hfdbg("  BASEPRI: %08x PRIMASK: %08x IPSR: %08x CONTROL: %08x\n",
        getbasepri(), getprimask(), getipsr(), getcontrol());
  hfdbg("  CFAULTS: %08x HFAULTS: %08x DFAULTS: %08x BFAULTADDR: %08x AFAULTS: %08x\n",
        getreg32(NVIC_CFAULTS), getreg32(NVIC_HFAULTS),
        getreg32(NVIC_DFAULTS), getreg32(NVIC_BFAULT_ADDR),
        getreg32(NVIC_AFAULTS));
  hfdbg("  R0: %08x %08x %08x %08x %08x %08x %08x %08x\n",
        regs[REG_R0],  regs[REG_R1],  regs[REG_R2],  regs[REG_R3],
        regs[REG_R4],  regs[REG_R5],  regs[REG_R6],  regs[REG_R7]);
  hfdbg("  R8: %08x %08x %08x %08x %08x %08x %08x %08x\n",
        regs[REG_R8],  regs[REG_R9],  regs[REG_R10], regs[REG_R11],
        regs[REG_R12], regs[REG_R13], regs[REG_R14], regs[REG_R15]);

#ifdef CONFIG_ARMV7M_USEBASEPRI
#  ifdef REG_EXC_RETURN
  hfdbg("  xPSR: %08x BASEPRI: %08x EXC_RETURN: %08x (saved)\n",
        current_regs[REG_XPSR],  current_regs[REG_BASEPRI],
        current_regs[REG_EXC_RETURN]);
#  else
  hfdbg("  xPSR: %08x BASEPRI: %08x (saved)\n",
        current_regs[REG_XPSR],  current_regs[REG_BASEPRI]);
#  endif
#else
#  ifdef REG_EXC_RETURN
  hfdbg("  xPSR: %08x PRIMASK: %08x EXC_RETURN: %08x (saved)\n",
        current_regs[REG_XPSR],  current_regs[REG_PRIMASK],
        current_regs[REG_EXC_RETURN]);
#  else
  hfdbg("  xPSR: %08x PRIMASK: %08x (saved)\n",
        current_regs[REG_XPSR],  current_regs[REG_PRIMASK]);
#  endif
#endif

  (void)irqsave();
  lldbg("PANIC!!! Hard fault: %08x\n", getreg32(NVIC_HFAULTS));
  PANIC();
  return OK;
}
// The static Cast method is used to obtain a pointer to the derived class object
EXPORT_C TReadPageTimeoutCompleteEvent& TReadPageTimeoutCompleteEvent::Cast(const THCIEventBase& aEvent)
	{
	__ASSERT_DEBUG(aEvent.EventCode() == ECommandCompleteEvent, PANIC(KSymbianCommandsEventsPanicCat, EWrongEventCode));
	__ASSERT_DEBUG(THCICommandCompleteEvent::Cast(aEvent).CommandOpcode() == KReadPageTimeoutOpcode, PANIC(KSymbianCommandsEventsPanicCat, EWrongEventCode));
	return *(reinterpret_cast<TReadPageTimeoutCompleteEvent*>(&const_cast<THCIEventBase&>(aEvent)));
	}
Esempio n. 24
0
void up_decodeirq(uint32_t* regs)
{
#ifdef CONFIG_SUPPRESS_INTERRUPTS
  lowsyslog(LOG_ERR, "Unexpected IRQ\n");
  current_regs = regs;
  PANIC();
#else
  /* Decode the interrupt.  First, fetch the interrupt id register. */

  uint16_t irqentry = getreg16(DM320_INTC_IRQENTRY0);

  /* The irqentry value is an offset into a table.  Zero means no interrupt. */

  if (irqentry != 0)
    {
      /* If non-zero, then we can map the table offset into an IRQ number */

      int irq = (irqentry >> 2) - 1;

      /* Verify that the resulting IRQ number is valid */

      if ((unsigned)irq < NR_IRQS)
        {
          /* Mask and acknowledge the interrupt */

          up_maskack_irq(irq);

          /* Current regs non-zero indicates that we are processing an interrupt;
           * current_regs is also used to manage interrupt level context switches.
           *
           * Nested interrupts are not supported.
           */

          DEBUGASSERT(current_regs == NULL);
          current_regs = regs;

          /* Deliver the IRQ */

          irq_dispatch(irq, regs);

#if defined(CONFIG_ARCH_FPU) || defined(CONFIG_ARCH_ADDRENV)
          /* Check for a context switch.  If a context switch occurred, then
           * current_regs will have a different value than it did on entry.
           * If an interrupt level context switch has occurred, then restore
           * the floating point state and the establish the correct address
           * environment before returning from the interrupt.
           */

          if (regs != current_regs)
            {
#ifdef CONFIG_ARCH_FPU
              /* Restore floating point registers */

              up_restorefpu((uint32_t*)current_regs);
#endif

#ifdef CONFIG_ARCH_ADDRENV
              /* Make sure that the address environment for the previously
               * running task is closed down gracefully (data caches dump,
               * MMU flushed) and set up the address environment for the new
               * thread at the head of the ready-to-run list.
               */

              (void)group_addrenv(NULL);
#endif
            }
#endif

          /* Set current_regs to NULL to indicate that we are no longer in
           * an interrupt handler.
           */

          current_regs = NULL;

          /* Unmask the last interrupt (global interrupts are still
           * disabled).
           */

          up_enable_irq(irq);
        }
    }
Esempio n. 25
0
void gp_handler(registers_t *regs)
{
  PANIC("General Protection Fault\n");
}
Esempio n. 26
0
static void report_push(void) {
	union {
		arp_report_t *a;
		ip_report_t *i;
		void *ptr;
	} pr_u;

	DBG(M_RPT, "in report_push r_type %d", r_type);

	switch (r_type) {
		case REPORT_TYPE_ARP:

			pr_u.ptr=xmalloc(sizeof(arp_report_t));
			memcpy(pr_u.ptr, (const void *)&r_u.a, sizeof(arp_report_t));
			pr_u.a->doff=0;

			if (s->ss->ret_layers > 0) {
				union {
					uint16_t *len;
					uint8_t *inc;
					void *ptr;
				} pk_u;

				if (p_len < 1) {
					PANIC("saved packet size is incorrect");
				}

				pk_u.ptr=xmalloc(p_len + sizeof(uint16_t));
				*pk_u.len=p_len;
				memcpy(pk_u.inc + sizeof(uint16_t), p_ptr, p_len);
				fifo_push(p_queue, pk_u.ptr);
				DBG(M_RPT, "pushed packet into p_queue");
				pr_u.a->doff=p_len;
			}

			fifo_push(r_queue, pr_u.ptr);
			DBG(M_RPT, "pushed report into r_queue");
			break;

		case REPORT_TYPE_IP:
			pr_u.ptr=xmalloc(sizeof(ip_report_t));
			memcpy(pr_u.ptr, (const void *)&r_u.i, sizeof(ip_report_t));
			pr_u.i->doff=0;

			if (s->ss->ret_layers > 0) {
				union {
					uint16_t *len;
					uint8_t *inc;
					void *ptr;
				} pk_u;

				if (p_len < 1) {
					PANIC("saved packet size is incorrect");
				}

				pk_u.ptr=xmalloc(p_len + sizeof(uint16_t));
				*pk_u.len=p_len;
				memcpy(pk_u.inc + sizeof(uint16_t), p_ptr, p_len);
				fifo_push(p_queue, pk_u.ptr);
				DBG(M_RPT, "pushed packet into p_queue");
				pr_u.i->doff=p_len;
			}

			fifo_push(r_queue, pr_u.ptr);

			DBG(M_RPT, "pushed report into r_queue");
			break;

		default:
			PANIC("unknown report type %d", r_type);
			break;
	}
}
Esempio n. 27
0
/*
 * Threaded process initialization.
 *
 * This is only called under two conditions:
 *
 *   1) Some thread routines have detected that the library hasn't yet
 *      been initialized (_thr_initial == NULL && curthread == NULL), or
 *
 *   2) An explicit call to reinitialize after a fork (indicated
 *      by curthread != NULL)
 */
void
_libpthread_init(struct pthread *curthread)
{
	int fd, first = 0;

	/* Check if this function has already been called: */
	if ((_thr_initial != NULL) && (curthread == NULL))
		/* Only initialize the threaded application once. */
		return;

	/*
	 * Check the size of the jump table to make sure it is preset
	 * with the correct number of entries.
	 */
	if (sizeof(jmp_table) != (sizeof(pthread_func_t) * PJT_MAX * 2))
		PANIC("Thread jump table not properly initialized");
	memcpy(__thr_jtable, jmp_table, sizeof(jmp_table));

	/*
	 * Check for the special case of this process running as
	 * or in place of init as pid = 1:
	 */
	if ((_thr_pid = getpid()) == 1) {
		/*
		 * Setup a new session for this process which is
		 * assumed to be running as root.
		 */
		if (setsid() == -1)
			PANIC("Can't set session ID");
		if (revoke(_PATH_CONSOLE) != 0)
			PANIC("Can't revoke console");
		if ((fd = __sys_open(_PATH_CONSOLE, O_RDWR)) < 0)
			PANIC("Can't open console");
		if (setlogin("root") == -1)
			PANIC("Can't set login to root");
		if (_ioctl(fd, TIOCSCTTY, (char *) NULL) == -1)
			PANIC("Can't set controlling terminal");
	}

	/* Initialize pthread private data. */
	init_private();

	/* Set the initial thread. */
	if (curthread == NULL) {
		first = 1;
		/* Create and initialize the initial thread. */
		curthread = _thr_alloc(NULL);
		if (curthread == NULL)
			PANIC("Can't allocate initial thread");
		init_main_thread(curthread);
	}
	/*
	 * Add the thread to the thread list queue.
	 */
	THR_LIST_ADD(curthread);
	_thread_active_threads = 1;

	/* Setup the thread specific data */
	_tcb_set(curthread->tcb);

	if (first) {
		_thr_initial = curthread;
		_thr_signal_init();
		if (_thread_event_mask & TD_CREATE)
			_thr_report_creation(curthread, curthread);
	}
}
Esempio n. 28
0
/* Saves the free map to disk */
void
free_map_save (void) 
{
  if (!bitmap_write (free_map, free_map_file))
    PANIC ("can't write free map");
}
Esempio n. 29
0
/*
 ***************************************************************************
 * Read stats for current activity from file and display them.
 *
 * IN:
 * @ifd		Input file descriptor.
 * @fpos	Position in file where reading must start.
 * @curr	Index in array for current sample statistics.
 * @rows	Number of rows of screen.
 * @act_id	Activity to display.
 * @file_actlst	List of activities in file.
 * @file	Name of file being read.
 * @file_magic	file_magic structure filled with file magic header data.
 *
 * OUT:
 * @curr	Index in array for next sample statistics.
 * @cnt		Number of remaining lines of stats to write.
 * @eosaf	Set to TRUE if EOF (end of file) has been reached.
 * @reset	Set to TRUE if last_uptime variable should be
 * 		reinitialized (used in next_slice() function).
 ***************************************************************************
 */
void handle_curr_act_stats(int ifd, off_t fpos, int *curr, long *cnt, int *eosaf,
                           int rows, unsigned int act_id, int *reset,
                           struct file_activity *file_actlst, char *file,
                           struct file_magic *file_magic)
{
    int p;
    unsigned long lines = 0;
    unsigned char rtype;
    int davg = 0, next, inc = -2;

    if (lseek(ifd, fpos, SEEK_SET) < fpos) {
        perror("lseek");
        exit(2);
    }

    /*
     * Restore the first stats collected.
     * Used to compute the rate displayed on the first line.
     */
    copy_structures(act, id_seq, record_hdr, !*curr, 2);

    *cnt  = count;

    /* Assess number of lines printed */
    if ((p = get_activity_position(act, act_id)) >= 0) {
        if (act[p]->bitmap) {
            inc = count_bits(act[p]->bitmap->b_array,
                             BITMAP_SIZE(act[p]->bitmap->b_size));
        }
        else {
            inc = act[p]->nr;
        }
    }
    if (inc < 0) {
        /* Should never happen */
        PANIC(inc);
    }

    do {
        /* Display count lines of stats */
        *eosaf = sa_fread(ifd, &record_hdr[*curr],
                          RECORD_HEADER_SIZE, SOFT_SIZE);
        rtype = record_hdr[*curr].record_type;

        if (!*eosaf && (rtype != R_RESTART) && (rtype != R_COMMENT)) {
            /* Read the extra fields since it's not a special record */
            read_file_stat_bunch(act, *curr, ifd, file_hdr.sa_act_nr, file_actlst);
        }

        if ((lines >= rows) || !lines) {
            lines = 0;
            dis = 1;
        }
        else
            dis = 0;

        if (!*eosaf && (rtype != R_RESTART)) {

            if (rtype == R_COMMENT) {
                /* Display comment */
                next = sar_print_special(*curr, tm_start.use, tm_end.use,
                                         R_COMMENT, ifd, file, file_magic);
                if (next) {
                    /* A line of comment was actually displayed */
                    lines++;
                }
                continue;
            }

            /* next is set to 1 when we were close enough to desired interval */
            next = write_stats(*curr, USE_SA_FILE, cnt, tm_start.use, tm_end.use,
                               *reset, act_id);
            if (next && (*cnt > 0)) {
                (*cnt)--;
            }
            if (next) {
                davg++;
                *curr ^=1;
                lines += inc;
            }
            *reset = FALSE;
        }
    }
    while (*cnt && !*eosaf && (rtype != R_RESTART));

    if (davg) {
        write_stats_avg(!*curr, USE_SA_FILE, act_id);
    }

    *reset = TRUE;
}
Esempio n. 30
0
void up_unblock_task(_TCB *tcb)
{
  /* Verify that the context switch can be performed */

  if ((tcb->task_state < FIRST_BLOCKED_STATE) ||
      (tcb->task_state > LAST_BLOCKED_STATE))
    {
      PANIC(OSERR_BADUNBLOCKSTATE);
    }
  else
    {
      _TCB *rtcb = (_TCB*)g_readytorun.head;

      /* Remove the task from the blocked task list */

      sched_removeblocked(tcb);

      /* Reset its timeslice.  This is only meaningful for round
       * robin tasks but it doesn't here to do it for everything
       */

#if CONFIG_RR_INTERVAL > 0
      tcb->timeslice = CONFIG_RR_INTERVAL / MSEC_PER_TICK;
#endif

      /* Add the task in the correct location in the prioritized
       * g_readytorun task list
       */

      if (sched_addreadytorun(tcb))
        {
          /* The currently active task has changed! We need to do
           * a context switch to the new task.
           *
           * Are we in an interrupt handler? 
           */

          if (current_regs)
            {
              /* Yes, then we have to do things differently.
               * Just copy the current_regs into the OLD rtcb.
               */

               up_savestate(rtcb->xcp.regs);

              /* Restore the exception context of the rtcb at the (new) head 
               * of the g_readytorun task list.
               */

              rtcb = (_TCB*)g_readytorun.head;

              /* Then switch contexts */

              up_restorestate(rtcb->xcp.regs);
            }

          /* We are not in an interrupt handler.  Copy the user C context
           * into the TCB of the task that was previously active.  if 
           * up_saveusercontext returns a non-zero value, then this is really the
           * previously running task restarting!
           */

          else if (!up_saveusercontext(rtcb->xcp.regs))
            {
              /* Restore the exception context of the new task that is ready to
               * run (probably tcb).  This is the new rtcb at the head of the
               * g_readytorun task list.
               */

              rtcb = (_TCB*)g_readytorun.head;

              /* Then switch contexts */

              up_fullcontextrestore(rtcb->xcp.regs);
            }
        }
    }
}